C#上传图片和生成缩略图以及图片预览

因工作需要,上传图片要增加MIME类型验证和生成较小尺寸的图片用于浏览。根据网上代码加以修改做出如下效果图:

前台代码如下:

 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head runat="server">
 3     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 4     <title>上传图片和生成缩略图以及图片预览</title>
 5     <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
 6     <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
 7     <script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
 8 </head>
 9 <body>
10     <form id="form1" runat="server">
11         <table>
12             <tr>
13                 <td>图片上传:
14                 </td>
15                 <td>
16                     <input type="text" id="txtImgPath" class="easyui-textbox" runat="server" style="width: 235px;" />
17                     <input type="button" id="btnPCImg" value="浏览..." onclick="showFileUp('FileUpload1')"
18                         class="easyui-linkbutton btn" style="width: 106px;" />
19                     <asp:FileUpload class="easyui-linkbutton btn" Style="display: none" ID="FileUpload1"
20                         runat="server" onchange="apendtoText('txtImgPath',this)" />
21                     <asp:Button class="easyui-linkbutton btn" ID="btnUpFile" runat="server" Text="上传图片"
22                         OnClick="btnUpFile_OnClick" Width="106px" />
23                 </td>
24             </tr>
25             <tr>
26                 <td>图片预览:
27                 </td>
28                 <td>
29                     <asp:Image ID="Image1" runat="server" />
30                     <asp:TextBox ID="txtimg" Style="display: none;" runat="server" Height="20px"></asp:TextBox>
31                     <asp:TextBox ID="oldimgpath" Style="display: none;" runat="server" Height="20px"></asp:TextBox>
32                 </td>
33             </tr>
34         </table>
35     </form>
36 </body>
37 <script type="text/javascript">
38     /*
39     * 显示文件选择框
40     * id {String} 要显示的FileUp
41     */
42     function showFileUp(id) {
43         $('#' + id).click();
44     }
45     /*
46     * FileUp控件值改变后将该控件的值赋给其他控件
47     * id {String} 接收值的控件ID
48     * obj {Object} FileUp控件
49     */
50     function apendtoText(id, obj) {
51         $('#' + id).textbox('setText', $(obj).val());
52     }
53 </script>
54 </html>
View Code

 后台代码如下:

  1         /// <summary>
  2         /// 上传图片
  3         /// </summary>
  4         /// <param name="sender"></param>
  5         /// <param name="e"></param>
  6         protected void btnUpFile_OnClick(object sender, EventArgs e)
  7         {
  8             if (FileUpload1.PostedFile.FileName != "")
  9             {
 10                 if (FileUpload1.PostedFile.ContentLength <= 2048000)//只能上传小于或等于2MB的图片
 11                 {
 12                     FileExtension[] fe = { FileExtension.Gif, FileExtension.Jpg, FileExtension.Png };//允许的图片格式
 13                     if (FileValidation.IsAllowedExtension(FileUpload1, fe))
 14                     {
 15                         //}
 16                         //if (newFileExtensions == ".jpg" || newFileExtensions == ".gif" || newFileExtensions == ".bmp" || newFileExtensions == ".png")//直接使用文件后缀检查是否为允许类型
 17                         //{
 18                         string sfilename = FileUpload1.PostedFile.FileName;
 19                         int sfilenamehz = sfilename.LastIndexOf(".", StringComparison.Ordinal);
 20                         string newFileExtensions = sfilename.Substring(sfilenamehz).ToLower();
 21                         string pa = "uploadfiles/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "/";//获取当前年份和月份作为文件夹名
 22                         if (!Directory.Exists("~/" + pa))//如不存在则创建文件夹
 23                         {
 24                             Directory.CreateDirectory(Server.MapPath("~/" + pa));
 25                         }
 26                         string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
 27                         string uppath = "~/" + pa + newFileName + newFileExtensions;
 28 
 29                         Stream oStream = FileUpload1.PostedFile.InputStream;
 30                         System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
 31 
 32                         int oWidth = oImage.Width; //原图宽度
 33                         int oHeight = oImage.Height; //原图高度
 34                         int tWidth = 200; //设置缩略图初始宽度
 35                         int tHeight = 200; //设置缩略图初始高度
 36 
 37                         //按比例计算出缩略图的宽度和高度
 38                         if (oWidth >= oHeight)
 39                         {
 40                             tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
 41                         }
 42                         else
 43                         {
 44                             tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
 45                         }
 46 
 47                         //生成缩略原图
 48                         Bitmap tImage = new Bitmap(tWidth, tHeight);
 49                         Graphics g = Graphics.FromImage(tImage);
 50                         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法
 51                         g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
 52                         g.Clear(Color.Transparent); //清空画布并以透明背景色填充
 53                         g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
 54 
 55                         string upfilepath2 = "~/" + pa + newFileName + "_m" + newFileExtensions; //缩略图为原图后缀增加_m用于区分
 56                         string oFullName = Server.MapPath(uppath);
 57                         string tFullName = Server.MapPath(upfilepath2);
 58 
 59                         try
 60                         {
 61                             //保存图片
 62                             oImage.Save(oFullName);
 63                             tImage.Save(tFullName);
 64                             Image1.ImageUrl = upfilepath2;//将缩略图显示到前台Img控件
 65                             txtimg.Text = pa + newFileName + "_m" + newFileExtensions;//将文件地址赋予控件用于保存
 66                         }
 67                         catch (Exception ex)
 68                         {
 69                             throw new Exception("发生错误,保存失败!", ex);
 70                         }
 71                         finally
 72                         {
 73                             //释放资源
 74                             oImage.Dispose();
 75                             g.Dispose();
 76                             tImage.Dispose();
 77                         }
 78                     }
 79                     else
 80                     {
 81                         string fileType = string.Empty;
 82                         foreach (var fileExtension in fe)
 83                         {
 84                             if (!string.IsNullOrEmpty(fileType))
 85                             {
 86                                 fileType += ",";
 87                             }
 88                             fileType += fileExtension;
 89                         }
 90                         Response.Write("<script>alert('文件格式被禁止,只支持" + fileType + "格式的图片')</script>");
 91                     }
 92                 }
 93                 else
 94                 {
 95                     Response.Write("<script>alert('文件大了,请修改大小,勿超过2MB')</script>");
 96                 }
 97             }
 98         }
 99         enum FileExtension
100         {
101             Jpg = 255216,
102             Gif = 7173,
103             Png = 13780
104         }
105         /// <summary>
106         /// 判断上传的文件的真实格式
107         /// </summary>
108         private class FileValidation
109         {
110             /// <summary>
111             /// 检查是否为允许的图片格式
112             /// </summary>
113             /// <param name="fu">上传控件</param>
114             /// <param name="fileEx">文件扩展名</param>
115             /// <returns></returns>
116             public static bool IsAllowedExtension(FileUpload fu, FileExtension[] fileEx)
117             {
118                 int fileLen = fu.PostedFile.ContentLength;
119                 byte[] imgArray = new byte[fileLen];
120                 fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);
121                 MemoryStream ms = new MemoryStream(imgArray);
122                 BinaryReader br = new BinaryReader(ms);
123                 string fileclass = string.Empty;
124                 try
125                 {
126                     byte buffer = br.ReadByte();
127                     fileclass = buffer.ToString();
128                     buffer = br.ReadByte();
129                     fileclass += buffer.ToString();
130                 }
131                 catch //(Exception ex)
132                 {
133                     // ignored
134                 }
135                 br.Close();
136                 ms.Close();
137                 int num = 0;
138                 int.TryParse(fileclass, out num);
139                 foreach (FileExtension fe in fileEx)
140                 {
141                     if (num == (int)fe)
142                         return true;
143                 }
144                 return false;
145             }
146         }

 

posted @ 2016-03-23 12:08  Idus  阅读(4422)  评论(0编辑  收藏  举报