在網站建設中,關於圖片是必不可少的,後臺管理中往往需要上傳圖片,大的圖片在網絡中傳輸速率很慢,很不理想,因此解決辦法是,用戶上傳圖片時候,保存一個圖片的縮略圖,在網頁顯示用縮略圖,用戶下載,使用原圖,下面是通過搜索資料,整理的c#關於保存圖片縮略圖的方法,用戶只需要傳入適當參數,調用此方法就可以生成縮略圖。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; public partial class upload : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } /// <summary> /// 圖片等比縮放 /// </summary> /// <param name="postedfile">原圖地址加名稱</param> /// <param name="savepath">縮略圖存放地址</param> /// <param name="smallname">縮略圖名稱</param> /// <param name="targetwidth">指定的最大寬度</param> /// <param name="targetheight">指定的最大高度</param> public static void zoomauto(string initpath, string savepath,string smallname, double targetwidth, double targetheight) { //虛擬路徑轉絕對路徑 initpath = System.Web.HttpContext.Current.Server.MapPath(initpath); savepath = System.Web.HttpContext.Current.Server.MapPath(savepath); //創建目錄 string dir = Path.GetDirectoryName(savepath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); //原始圖片(獲取原始圖片創建對象,並使用流中嵌入的顏色管理信息) System.Drawing.Image initimage = System.Drawing.Image.FromFile(initpath); //原圖寬高均小於模版,不作處理,直接保存 if (initimage.Width <= targetwidth && initimage.Height <= targetheight) { //保存 initimage.Save(savepath + smallname, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //縮略圖寬、高計算 double newwidth = initimage.Width; double newheight = initimage.Height; //寬大於高或寬等於高(橫圖或正方) if (initimage.Width > initimage.Height || initimage.Width == initimage.Height) { //如果寬大於模版 if (initimage.Width > targetwidth) { //寬按模版,高按比例縮放 newwidth = targetwidth; newheight = initimage.Height * (targetwidth / initimage.Width); } } //高大於寬(豎圖) else { //如果高大於模版 if (initimage.Height > targetheight) { //高按模版,寬按比例縮放 newheight = targetheight; newwidth = initimage.Width * (targetheight / initimage.Height); } } //生成新圖 //新建一個bmp圖片 System.Drawing.Image newimage = new System.Drawing.Bitmap((int)newwidth, (int)newheight); //新建一個畫板 System.Drawing.Graphics newg = System.Drawing.Graphics.FromImage(newimage); //設置質量 newg.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; newg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //置背景色 newg.Clear(System.Drawing.Color.White); //畫圖 newg.DrawImage(initimage, new System.Drawing.Rectangle(0, 0, newimage.Width, newimage.Height), new System.Drawing.Rectangle(0, 0, initimage.Width, initimage.Height), System.Drawing.GraphicsUnit.Pixel); //保存縮略圖 newimage.Save(savepath + smallname, System.Drawing.Imaging.ImageFormat.Jpeg); //釋放資源 newg.Dispose(); newimage.Dispose(); initimage.Dispose(); } } }