使用ASP.net(C#)批量上传图片并自动生成缩略图,文字水印图,图片水印图

介绍了一个ASP.NET平台上的C#程序,实现批量上传图片至服务器的功能。程序支持自定义目录、自动创建目录、生成缩略图及添加文字或图片水印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 因本网站上传图片的需要,参考很多成熟的经验,在ASP.net平台上使用C#语言,做了这一自动批量上传图片的.ASPX文件,并经调试成功,在本网站上使用,现发出来供大家参考,也希望高手多加指点。
  2.         本程序主要功能有:
  3.         (1)可以根据自己的需要更改上传到服务器上的目录,上传的源图、缩略图、文字水印图和图片水印图分别存入所定目录下的不同目录;
  4.         (2)自动检查目录,如无所选择的目录,则自动创建它们;
  5.         (3)自行设定生成缩略图的大小;
  6.         (4)可以选择是否需要生成文字水印、图片水印,默认为不生成水印图;
  7.         (5)可以添加、删除所需上传的图片。
  8.         在本程序中均加了相关注释,所以直接发代码,不再多作解释。
  9.    后台程序:
  10. using System;
  11. using System.Collections;
  12. using System.Configuration;
  13. using System.Data;
  14. using System.Linq;
  15. using System.Web;
  16. using System.Web.Security;
  17. using System.Web.UI;
  18. using System.Web.UI.HtmlControls;
  19. using System.Web.UI.WebControls;
  20. using System.Web.UI.WebControls.WebParts;
  21. using System.Xml.Linq;
  22. using System.IO;
  23. using System.Net;
  24. using System.Text.RegularExpressions;
  25. /// 〈summary>
  26. /// FileUpload1.HasFile  如果是true,则表示该控件有文件要上传
  27. /// FileUpload1.FileName  返回要上传文件的名称,不包含路径信息
  28. /// FileUpload1.FileContent  返回一个指向上传文件的流对象
  29. /// FileUpload1.PostedFile   返回已经上传文件的引用
  30. /// FileUpload1.PostedFile.ContentLength  返回上传文件的按字节表示的文件大小
  31. /// FileUpload1.PostedFile.ContentType    返回上传文件的MIME内容类型,也就是文件类型,如返回"image/jpg"
  32. /// FileUpload1.PostedFile.FileName       返回文件在客户端的完全路径(包括文件名全称)
  33. /// FileUpload1.PostedFile.InputStream    返回一个指向上传文件的流对象
  34. /// FileInfo对象表示磁盘或网络位置上的文件。提供文件的路径,就可以创建一个FileInfo对象:
  35. /// 〈/summary>
  36. public partial class BackManagement_ImagesUpload : System.Web.UI.Page
  37. {
  38.     public string treePath = "";
  39.     public int imageW = 100;
  40.     public int imageH = 100;
  41.     protected void Page_Load(object sender, EventArgs e)
  42.     {
  43.         this.Button5.Attributes.Add("Onclick""window.close();"); //在本地关闭当前页,而不需要发送到服务器去关闭当前页时
  44.         if (!Page.IsPostBack)
  45.         {
  46.             Label2.Text = Server.MapPath("/");
  47.             TextBox3.Text = "ImageUpload";
  48.             treePath = Server.MapPath("/") + TextBox3.Text.Trim() + "/";
  49.             TextBox4.Text = imageW.ToString();
  50.             TextBox5.Text = imageH.ToString();
  51.         }
  52.     }
  53.     protected void btnload_Click(object sender, EventArgs e)
  54.     {
  55.         //如果保存图片的目录不存在,由创建它
  56.         treePath = Server.MapPath("/") + TextBox3.Text.Trim() + "/";
  57.         imageW = Convert.ToInt32(TextBox4.Text.ToString());
  58.         imageH = Convert.ToInt32(TextBox5.Text.ToString());
  59.         if (!File.Exists(treePath + "images"))   //如果/ImageUpload/images不存在,则创建/ImageUpload/images,用于存放源图片
  60.         {
  61.             System.IO.Directory.CreateDirectory(treePath + "images");
  62.         }
  63.         if (!File.Exists(treePath + "thumbnails"))   //如果/ImageUpload/thumbnails不存在,则创建/ImageUpload/thumbnails,用于存放缩略图片
  64.         {
  65.             System.IO.Directory.CreateDirectory(treePath + "thumbnails");
  66.         }
  67.         if (!File.Exists(treePath + "textImages"))   //如果/ImageUpload/textImages不存在,则创建/ImageUpload/textImages,用于存文字水印图片
  68.         {
  69.             System.IO.Directory.CreateDirectory(treePath + "textImages");
  70.         }
  71.         if (!File.Exists(treePath + "waterImages"))   //如果/ImageUpload/waterImages不存在,则创建/ImageUpload/waterImages,用于存图形水印图片
  72.         {
  73.             System.IO.Directory.CreateDirectory(treePath + "waterImages");
  74.         }
  75.         if (FileUpload1.HasFile)   //如果是true,则表示该控件有文件要上传
  76.         {
  77.             string fileContentType = FileUpload1.PostedFile.ContentType;
  78.             if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
  79.             {
  80.                 string name = FileUpload1.PostedFile.FileName;                         //返回文件在客户端的完全路径(包括文件名全称)
  81.                 FileInfo file = new FileInfo(name);                                    //FileInfo对象表示磁盘或网络位置上的文件。提供文件的路径,就可以创建一个FileInfo对象:
  82.                 string fileName = file.Name;                                           // 文件名称
  83.                 string fileName_s = "x_" + file.Name;                                  // 缩略图文件名称
  84.                 string fileName_sy = "text_" + file.Name;                              // 水印图文件名称(文字)
  85.                 string fileName_syp = "water_" + file.Name;                            // 水印图文件名称(图片)
  86.                 string webFilePath = treePath + "images/" + fileName;          // 服务器端文件路径
  87.                 string webFilePath_s = treePath + "thumbnails/" + fileName_s;    // 服务器端缩略图路径
  88.                 string webFilePath_sy = treePath + "textImages/" + fileName_sy;   // 服务器端带水印图路径(文字)
  89.                 string webFilePath_syp = treePath + "waterImages/" + fileName_syp; // 服务器端带水印图路径(图片)
  90.                 string webFilePath_sypf = Server.MapPath("../images/tzwhx.png");               // 服务器端水印图路径(图片)
  91.                 
  92.                 if (!File.Exists(webFilePath))
  93.                 {
  94.                     try
  95.                     {
  96.                         FileUpload1.SaveAs(webFilePath);                                // 使用 SaveAs 方法保存文件
  97.                         if (CheckBox1.Checked)                                          //是否生成文字水印图
  98.                         {
  99.                             AddWater(webFilePath, webFilePath_sy);
  100.                         }
  101.                         if (CheckBox2.Checked)                                          //是否生成图形水印图
  102.                         {
  103.                             AddWaterPic(webFilePath, webFilePath_syp, webFilePath_sypf);
  104.                         }
  105.                         MakeThumbnail(webFilePath, webFilePath_s, imageW, imageH, "Cut");     // 生成缩略图方法
  106.                         Label1.Text = "提示:文件“" + fileName + "”成功上传,并生成“" + fileName_s + "”缩略图,文件类型为:" + FileUpload1.PostedFile.ContentType + ",文件大小为:" + FileUpload1.PostedFile.ContentLength + "B";
  107.                         Image1.ImageUrl = "/" + TextBox3.Text.ToString() + "/images/" + fileName;
  108.                         TextBox1.Text = webFilePath;
  109.                         TextBox2.Text = "/" + TextBox3.Text.ToString() + "/images/" + fileName;
  110.                     }
  111.                     catch (Exception ex)
  112.                     {
  113.                         Label1.Text = "提示:文件上传失败,失败原因:" + ex.Message;
  114.                     }
  115.                 }
  116.                 else
  117.                 {
  118.                     Label1.Text = "提示:文件已经存在,请重命名后上传";
  119.                 }
  120.             }
  121.             else
  122.             {
  123.                 Label1.Text = "提示:文件类型不符";
  124.             }
  125.         }
  126.     }
  127.     /**/
  128.     /// 〈summary>
  129.     /// 生成缩略图
  130.     /// 〈/summary>
  131.     /// 〈param name="originalImagePath">源图路径(物理路径)〈/param>
  132.     /// 〈param name="thumbnailPath">缩略图路径(物理路径)〈/param>
  133.     /// 〈param name="width">缩略图宽度〈/param>
  134.     /// 〈param name="height">缩略图高度〈/param>
  135.     /// 〈param name="mode">生成缩略图的方式〈/param>    
  136.     public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
  137.     {
  138.         System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
  139.         int towidth = width;
  140.         int toheight = height;
  141.         int x = 0;
  142.         int y = 0;
  143.         int ow = originalImage.Width;
  144.         int oh = originalImage.Height;
  145.         switch (mode)
  146.         {
  147.             case "HW"://指定高宽缩放(可能变形)                
  148.                 break;
  149.             case "W"://指定宽,高按比例                    
  150.                 toheight = originalImage.Height * width / originalImage.Width;
  151.                 break;
  152.             case "H"://指定高,宽按比例
  153.                 towidth = originalImage.Width * height / originalImage.Height;
  154.                 break;
  155.             case "Cut"://指定高宽裁减(不变形)                
  156.                 if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
  157.                 {
  158.                     oh = originalImage.Height;
  159.                     ow = originalImage.Height * towidth / toheight;
  160.                     y = 0;
  161.                     x = (originalImage.Width - ow) / 2;
  162.                 }
  163.                 else
  164.                 {
  165.                     ow = originalImage.Width;
  166.                     oh = originalImage.Width * height / towidth;
  167.                     x = 0;
  168.                     y = (originalImage.Height - oh) / 2;
  169.                 }
  170.                 break;
  171.             default:
  172.                 break;
  173.         }
  174.         //新建一个bmp图片
  175.         System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
  176.         //新建一个画板
  177.         System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
  178.         //设置高质量插值法
  179.         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  180.         //设置高质量,低速度呈现平滑程度
  181.         g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  182.         //清空画布并以透明背景色填充
  183.         g.Clear(System.Drawing.Color.Transparent);
  184.         //在指定位置并且按指定大小绘制原图片的指定部分
  185.         g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
  186.             new System.Drawing.Rectangle(x, y, ow, oh),
  187.             System.Drawing.GraphicsUnit.Pixel);
  188.         try
  189.         {
  190.             //以jpg格式保存缩略图
  191.             bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
  192.         }
  193.         catch (System.Exception e)
  194.         {
  195.             throw e;
  196.         }
  197.         finally
  198.         {
  199.             originalImage.Dispose();
  200.             bitmap.Dispose();
  201.             g.Dispose();
  202.         }
  203.     }
  204.     /**/
  205.     /// 〈summary>
  206.     /// 在图片上增加文字水印
  207.     /// 〈/summary>
  208.     /// 〈param name="Path">原服务器图片路径〈/param>
  209.     /// 〈param name="Path_sy">生成的带文字水印的图片路径〈/param>
  210.     protected void AddWater(string Path, string Path_sy)
  211.     {
  212.         string addText = "www.tzwhx.com";
  213.         System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
  214.         System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  215.         g.DrawImage(image, 0, 0, image.Width, image.Height);
  216.         System.Drawing.Font f = new System.Drawing.Font("Verdana", 10);    //字体位置为左空10
  217.         System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Green);
  218.         g.DrawString(addText, f, b, 14, 14);    //字体大小为14X14
  219.         g.Dispose();
  220.         image.Save(Path_sy);
  221.         image.Dispose();
  222.     }
  223.     /**/
  224.     /// 〈summary>
  225.     /// 在图片上生成图片水印
  226.     /// 〈/summary>
  227.     /// 〈param name="Path">原服务器图片路径〈/param>
  228.     /// 〈param name="Path_syp">生成的带图片水印的图片路径〈/param>
  229.     /// 〈param name="Path_sypf">水印图片路径〈/param>
  230.     protected void AddWaterPic(string Path, string Path_syp, string Path_sypf)
  231.     {
  232.         System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
  233.         System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_sypf);
  234.         System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  235.         g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
  236.         g.Dispose();
  237.         image.Save(Path_syp);
  238.         image.Dispose();
  239.     }
  240.     protected void Button2_Click(object sender, EventArgs e)
  241.     {
  242.         //自动保存远程图片
  243.         WebClient client = new WebClient();
  244.         //备用Reg:〈img.*?src=([/"/'])(http:////.+/.(jpg|gif|bmp|bnp))/1.*?>
  245.         Regex reg = new Regex("IMG[^>]*?src//s*=//s*(?:/"(?〈1>[^/"]*)/"|'(?〈1>[^/']*)')", RegexOptions.IgnoreCase);
  246.         MatchCollection m = reg.Matches(TextBox1.Text);
  247.         foreach (Match math in m)
  248.         {
  249.             string imgUrl = math.Groups[1].Value;
  250.             //在原图片名称前加YYMMDD重名名并上传
  251.             Regex regName = new Regex(@"/w+.(?:jpg|gif|bmp|png)", RegexOptions.IgnoreCase);
  252.             string strNewImgName = DateTime.Now.ToShortDateString().Replace("-""") + regName.Match(imgUrl).ToString();
  253.             try
  254.             {
  255.                 //保存图片
  256.                 //client.DownloadFile(imgUrl, Server.MapPath("../ImageUpload/Auto/" + strNewImgName));
  257.                 
  258.             }
  259.             catch
  260.             {
  261.             }
  262.             finally
  263.             {
  264.             }
  265.             client.Dispose();
  266.         }
  267.         Response.Write("〈script>alert('远程图片保存成功,保存路径为ImageUpload/auto')〈/script>");
  268.     }
  269. }
  270.     前台代码:
  271.  〈%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImagesAutoUpload.aspx.cs" Inherits="BackManagement_ImagesAutoUpload" %>
  272. 〈!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  273. 〈html xmlns="http://www.w3.org/1999/xhtml">
  274. 〈head id="Head1" runat="server">
  275.     〈title>自动上传图片并加文字水印〈/title>
  276. 〈/head>
  277. 〈body>
  278.     〈form id="form1" runat="server" method="post" enctype="multipart/form-data">
  279.     〈label for="pagebody1" style="display: none">
  280.     〈/label>
  281.     〈fieldset id="container">
  282.         〈legend>上传图片并加文字水印〈/legend>
  283.         〈div class="window" style="list-style: none;">
  284.             〈div style="padding: 0px; width: 808px; height: 200px; float: left; margin-right: 0px;">
  285.                 〈ul>
  286.                     〈li style="width: 150px; margin: 0px; padding: 0px; float: left;">
  287.                         〈asp:Image ID="Image1" runat="server" Height="200px" BorderWidth="2px" Width="150px"
  288.                             ImageUrl="~/images/Jpg/135X67/0_11_16.gif" />
  289.                     〈/li>
  290.                     〈li style="width: 250px; margin: 0px;">
  291.                         〈asp:ListBox ID="FileList" runat="server" Width="250px" Height="200px">〈/asp:ListBox>
  292.                     〈/li>
  293.                     〈li style="width: 400px; margin: 0px; float: right;">
  294.                         (1)图片将保存在你网站根目录〈asp:TextBox ID="TextBox3" runat="server">〈/asp:TextBox>中,你可以修改它,但建议你使用默认目录。〈br />
  295.                         (2)上传图片保存在所建目录的子目录 /images下;缩略图在 /thumbnails下;文字水印图在 /textImages下;图形水印图在 /waterImages目录下。〈br />
  296.                         (3)生成的缩略图的默认宽度和高度均为100px,你也可以修改它们,宽为: 〈asp:TextBox ID="TextBox4" runat="server" Width="54px">〈/asp:TextBox>高为:〈asp:TextBox
  297.                             ID="TextBox5" runat="server" Width="56px">〈/asp:TextBox>〈br />
  298.                         〈asp:CheckBox ID="CheckBox1" runat="server" Text="文字水印" />
  299.                         〈asp:CheckBox ID="CheckBox2" runat="server" Text="图形水印" />
  300.                             你可以选择是否生成水印图,默认不生成。 〈/li>
  301.                 〈/ul>
  302.             〈/div>
  303.         〈/div>
  304.         〈div>
  305.             〈asp:FileUpload ID="FindFile" runat="server" Width="529px" />
  306.         〈/div>
  307.         〈div>
  308.             〈asp:TextBox ID="TipInfo" runat="server" Width="400px">〈/asp:TextBox>
  309.             〈asp:TextBox ID="TextBox1" runat="server" Width="400px">〈/asp:TextBox>
  310.         〈/div>
  311.         〈div>
  312.             〈asp:Button ID="Upload" runat="server" Text="上  传" Style="height: 26px" OnClick="Upload_Click" />
  313.             〈asp:Button ID="AddFile" runat="server" Text="添  加" OnClick="AddFile_Click1" />
  314.             〈asp:Button ID="AddAllFile" runat="server" Text="全部添加" OnClick="AddAllFile_Click"
  315.                 Enabled="False" />
  316.             〈asp:Button ID="DelFile" runat="server" Text="删  除" OnClick="DelFile_Click1" />
  317.             〈asp:Button ID="btnExit" runat="server" Text="完  成" />
  318.         〈/div>
  319.         〈div>
  320.             
  321.         〈/div>
  322.     〈/fieldset>
  323.     〈/form>
  324. 〈/body>
  325. 〈/html>
  326.         另外,为解决大文件上传的限制,你必须在Web.config中加入以下代码。
  327.  < system.web>
  328.     < httpRuntime executionTimeout="90" maxRequestLength="20000" useFullyQualifiedRedirectUrl="false" requestLengthDiskThreshold="8192"/>
  329. < /system.web>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值