介面:
前台所用控制項:一個FileUpload用來瀏覽,一個Button用來上傳,一個Image用來顯示上傳的圖片
前台代碼:
<div> <asp:FileUpload ID="FileUpimage" runat="server" /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上傳" /> <asp:Image ID="Image1" runat="server" ImageUrl="~/image/save.png" Visible="False" /></div>
後台代碼:
/// <summary> /// 上傳 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { //判斷上傳控制項中是否有值 if (FileUpimage.HasFile == false) { Response.Write("<script>alert('請指定上傳的頭像')</script>"); } else { string fType = FileUpimage.PostedFile.ContentType;//擷取映像的類型 if (fType == "image/bmp" || fType == "image/gif" || fType == "image/pjpeg" || fType == "image/jpeg" || fType == "image/x-png" || fType == "image/png") { //擷取檔案資訊 FileInfo file = new FileInfo(FileUpimage.PostedFile.FileName); ///隨機資料 Guid guid = Guid.NewGuid(); string stamp = guid.ToString("N"); //產生隨機數 Random aa=new Random(); string number=aa.Next(10000).ToString(); //原始圖片儲存路徑 string path = "~/Files/" + stamp + ".gif"; //縮圖儲存路徑 string spath = "~/Files/" + number + ".gif"; try { //原始圖片儲存 FileUpimage.SaveAs(Server.MapPath(path)); //縮圖儲存 MakeThumbImage(Server.MapPath(path), Server.MapPath(spath), 200, 100); //給隱藏的圖片控制項賦值並顯示 Image1.Visible = true; Image1.ImageUrl = spath; Response.Write("<script>alert('上傳成功')</script>"); } catch { Response.Write("<script>alert('上傳失敗')</script>"); } } else { Response.Write("<script>alert('上傳頭像格式不正確')</script>"); } } } ///<summary> ///方法名稱:MakeThumbImage ///內容摘要:產生縮圖 /// </summary> /// <param name="sPath">源圖路徑(實體路徑)</param> /// <param name="stPath">縮圖路徑(實體路徑)</param> /// <param name="nWidth">縮圖寬度</param> /// <param name="nHeight">縮圖高度</param> private void MakeThumbImage(string sPath, string stPath, int nWidth, int nHeight) { System.Drawing.Image sImage = System.Drawing.Image.FromFile(sPath); int tw = nWidth; int th = nHeight; //原始圖片的寬度和高度 int sw = sImage.Width; int sh = sImage.Height; if (sw > tw) { sw = tw; } if (sh > th) { sh = th; } System.Drawing.Bitmap objPic, objNewPic; //映像對象 objPic = new System.Drawing.Bitmap(sPath); objNewPic = new System.Drawing.Bitmap(objPic, sw, sh); //使用指定的大小初始化objNewPic objNewPic.Save(stPath); sImage.Dispose(); //釋放資源 objPic.Dispose(); objNewPic.Dispose(); }