Asp.Net上傳圖片同時產生高清晰縮圖_實用技巧

來源:互聯網
上載者:User

在asp.net中,上傳圖片功能或者是常用的,產生縮圖也是常用的。baidu或者google,c#的方法也是很多的,但是一用卻發現縮圖不清晰啊,縮圖片太大之類的事情,下面是我在處理圖片上的代碼,效果不錯,所以拿出來分享,(效果能達到一些繪圖軟體的效果)

代碼如下:

 /// <summary>  /// asp.net上傳圖片並產生縮圖  /// </summary>  /// <param name="upImage">HtmlInputFile控制項</param>  /// <param name="sSavePath">儲存的路徑,些為相對伺服器路徑的下的檔案夾</param>  /// <param name="sThumbExtension">縮圖的thumb</param>  /// <param name="intThumbWidth">產生縮圖的寬度</param>  /// <param name="intThumbHeight">產生縮圖的高度</param>  /// <returns>縮圖名稱</returns>  public string UpLoadImage(HtmlInputFile upImage, string sSavePath, string sThumbExtension, int intThumbWidth, int intThumbHeight)  {   string sThumbFile = "";   string sFilename = "";     if (upImage.PostedFile != null)   {    HttpPostedFile myFile = upImage.PostedFile;    int nFileLen = myFile.ContentLength;    if (nFileLen == 0)     return "沒有選擇上傳圖片";       //擷取upImage選擇檔案的副檔名    string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower();    //判斷是否為圖片格式    if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png")     return "圖片格式不正確";        byte[] myData = new Byte[nFileLen];    myFile.InputStream.Read(myData, 0, nFileLen);    sFilename = System.IO.Path.GetFileName(myFile.FileName);    int file_append = 0;    //檢查當前檔案夾下是否有同名圖片,有則在檔案名稱+1    while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))    {     file_append++;     sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)      + file_append.ToString() + extendName;    }    System.IO.FileStream newFile     = new System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename),     System.IO.FileMode.Create, System.IO.FileAccess.Write);    newFile.Write(myData, 0, myData.Length);    newFile.Close();    //以上為上傳原圖    try    {     //原圖載入     using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))     {      //原圖寬度和高度      int width = sourceImage.Width;      int height = sourceImage.Height;      int smallWidth;      int smallHeight;      //擷取第一張繪製圖的大小,(比較 原圖的寬/縮圖的寬 和 原圖的高/縮圖的高)      if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)      {       smallWidth = intThumbWidth;       smallHeight = intThumbWidth * height / width;      }      else      {       smallWidth = intThumbHeight * width / height;       smallHeight = intThumbHeight;      }      //判斷縮圖在當前檔案夾下是否同名稱檔案存在      file_append = 0;      sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + extendName;      while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile)))      {       file_append++;       sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +        file_append.ToString() + extendName;      }      //縮圖儲存的絕對路徑      string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;      //建立一個圖板,以最小等比例壓縮大小繪製原圖      using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))      {       //繪製中間圖       using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))       {        //高清,平滑        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;        g.Clear(Color.Black);        g.DrawImage(        sourceImage,        new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),        new System.Drawing.Rectangle(0, 0, width, height),        System.Drawing.GraphicsUnit.Pixel        );       }       //建立一個圖板,以縮圖大小繪製中間圖       using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))       {      //繪製縮圖 http://www.cnblogs.com/sosoft/        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))        {         //高清,平滑         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;         g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;         g.Clear(Color.Black);         int lwidth = (smallWidth - intThumbWidth) / 2;         int bheight = (smallHeight - intThumbHeight) / 2;         g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);         g.Dispose();         bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);        }       }      }     }    }    catch    {     //出錯則刪除     System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename));     return "圖片格式不正確";    }    //返回縮圖名稱    return sThumbFile;   }   return "沒有選擇圖片";  }

HtmlInputFile控制項我想大家都應該知道的,就是input type=file....

下面把調用代碼也一起C上來

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">  <title>圖片上傳-柯樂義</title> </head> <body>  <form id="form1" runat="server">  <div>     <input id="File1" runat="server" type="file" /></div><asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />  </form> </body> </html>

 protected void Button1_Click(object sender, EventArgs e)  {   string a = this.UpLoadImage(this.File1, "UpLoad/", "thumb_", 118, 118);   }

這樣就會在你的UpLoad檔案夾下多出兩張圖片,一張是原圖,一張是縮圖。

提供一個更好的演算法,由於沒有時間去測試和調試,僅供參考

即,在第一步等比例縮小的時候,可以分多次,即把原圖到上面代碼的中間圖以百分比縮小,

例如:原圖為500*500 我要縮減成100*80,上面代碼程式會先繪製一張100*100的中間圖,再在這圖片上繪製100*80的,在繪製100*100中間圖之前如果先繪300*300的中間圖,再在300*300的基礎上再繪100*100然後再繪100*80這樣會比我上面的代碼效果更好,圖片更清晰,即中間圖越多,效果越好,大家可以去試試。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.