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 }

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com