網站後台都需要有上傳圖片的功能,下面的例子就是實現有關圖片上傳。缺點:圖片上傳到本服務器上,不適合大量圖片上傳
第一、圖片上傳,代碼如下: xxx.aspx 代碼如下: <td class="style1"> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button1" runat="server" Text="上傳一般圖片" onclick="Button1_Click" /> </td> <td class="style3"> <asp:Image ID="Image1" runat="server" Height="200px" Width="200px" /> </td> xxx.aspx.cs 代碼如下: protected void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFile file = Request.Files[i]; if (file.ContentLength > 0) { if (file.ContentType.Contains("image/")) { using (System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream)) { string FileName = System.IO.Path.GetFileName(file.FileName); string[] SplitFileName = FileName.Split('.'); string AtterFileName = DateTime.Now.ToString("yyyMMddHHmmss")+"." + SplitFileName[1]; img.Save(Server.MapPath("/upload/" + AtterFileName)); this.Image1.ImageUrl = "upload/" + AtterFileName; } } else { Response.Write("<script>alert('該文件不是圖片格式!');</script>"); } } else { Response.Write("<script>alert('請選擇要上傳的圖片');</script>"); } } } 第二、添加文字水印的圖片上傳,代碼如下: xxx.aspx 代碼如下: <td class="style1"> <asp:FileUpload ID="FileUpload2" runat="server" /> <asp:Button ID="Button2" runat="server" Text="上傳文字圖片" onclick="Button2_Click" /> </td> <td> <asp:Image ID="Image2" runat="server" Height="200px" Width="200px" /> </td> xxx.aspx.cs 代碼如下: protected void Button2_Click(object sender, EventArgs e) { for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFile file = Request.Files[i]; if (file.ContentLength > 0) { if (file.ContentType.Contains("image/")) { using (System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream)) { using (Graphics g = Graphics.FromImage(img)) { g.DrawString("我的圖片", new Font("宋體", 14), Brushes.Red, 0, 0); } string FileName = System.IO.Path.GetFileName(file.FileName); string[] SplitFileName = FileName.Split('.'); string AtterFileName = DateTime.Now.ToString("yyyMMddHHmmss") + "." + SplitFileName[1]; img.Save(Server.MapPath("/upload/" + AtterFileName)); this.Image2.ImageUrl = "upload/" + AtterFileName; } } else { Response.Write("<script>alert('該文件不是圖片格式!');</script>"); } } else { Response.Write("<script>alert('請選擇要上傳的圖片');</script>"); } } }