標籤:des style blog http color os io 檔案
產生縮圖核心代碼:
/// <summary> /// 圖片上傳 產生縮圖 /// </summary> /// <param name="files">檔案上傳控制項</param> /// <param name="path">檔案夾名稱</param> /// <param name="fname">檔案名稱</param> /// <param name="w">縮圖寬度</param> /// <param name="h">縮圖高度</param> public static void UploadImageThumbs(HttpPostedFile files, string filePath, string fname, int w, int h) { if (UtilsFile.IsOrNoFileUp(files) && fname.Equals(String.Empty) == false) { UtilsFile.DirectorysCreate(filePath); Image image = Image.FromStream(files.InputStream, true); //等比例縮放 if (w > 0 && h > 0) { if (image.Width > image.Height) { if (image.Width > w) h = (int)(image.Height * ((decimal)w / image.Width)); else { h = image.Height; w = image.Width; } } else { if (image.Height > h) w = (int)(image.Width * ((decimal)h / image.Height)); else { h = image.Height; w = image.Width; } } } else if (w > 0 && h == 0) { if (image.Width < w) w = image.Width; h = (int)(image.Height * ((decimal)w / image.Width)); } else if (w == 0 && h > 0) { if (image.Height < h) h = image.Height; w = (int)(image.Width * ((decimal)h / image.Height)); } else { w = image.Width; h = image.Height; } Bitmap ret = new Bitmap(w, h); using (Graphics g = Graphics.FromImage(ret)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(Brushes.White, 0, 0, w, h); g.DrawImage(image, 0, 0, w, h); EncoderParameters parms = new EncoderParameters(); long[] quality = new long[1]; quality[0] = 80; EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); parms.Param[0] = parm; ImageCodecInfo[] arr = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ar = null; for (int x = 0; x < arr.Length; x++) { if (arr[x].FormatDescription.Equals("JPEG")) { ar = arr[x]; break; } } ret.Save(filePath + fname, ar, parms); ret.Dispose(); image.Dispose(); } } }
總結:以上產生縮圖代碼,效果是比較好的,就是有時候紅色的點會失真,比較無解。不過這問題基本可以忽略不計。較真的朋友,如有較好的產生代碼,可以共用。
原文轉載: http://www.dyxue.com/tech/id2498.html