C#生成高清縮略圖代碼,一個C#函數模塊,內含注釋,後附函數參數,下面來看這個C#生成縮略圖代碼:
01public static void SetGoodImage(string fileName, string newFile, int maxHeight, int maxWidth,long qualitys)
02{
03 if (qualitys == 0)
04 {
05 qualitys = 80;
06 }
07 using (System.Drawing.Image img = System.Drawing.Image.FromFile(fileName))
08 {
09 System.Drawing.Imaging.ImageFormat
10 thisFormat = img.RawFormat;
11 Size newSize = NewSize(maxWidth, maxHeight, img.Width, img.Height);
12 Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
13 Graphics g = Graphics.FromImage(outBmp);
14 // 設置畫布的描繪質量
15 g.CompositingQuality = CompositingQuality.HighQuality;
16 g.SmoothingMode = SmoothingMode.HighQuality;
17 g.InterpolationMode = InterpolationMode.HighQualityBicubic;
18 g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height),
19 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
20 g.Dispose();
21 // 以下代碼為保存圖片時,設置壓縮質量
22 EncoderParameters encoderParams = new EncoderParameters();
23 long[] quality = new long[1];
24 quality[0] = qualitys;
25 EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
26 encoderParams.Param[0] = encoderParam;
27 //獲得包含有關內置圖像編碼解碼器的信息的ImageCodecInfo 對象.
28 ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
29 ImageCodecInfo jpegICI = null;
30 for (int x = 0;
31 x < arrayICI.Length;
32 x++)
33 {
34 if (arrayICI[x].FormatDescription.Equals("JPEG"))
35 {
36 jpegICI = arrayICI[x];
37 //設置JPEG編碼
38 break;
39 }
40 }
41 if (jpegICI != null)
42 {
43 outBmp.Save(newFile, jpegICI, encoderParams);
44 }
45 else
46 {
47 outBmp.Save(newFile, thisFormat);
48 }
49 img.Dispose();
50 outBmp.Dispose();
51 }
52}
函數參數說明:
view sourceprint?1/// 原文件
2/// 新文件
3/// 最大高度
4/// 最大寬度
5/// 質量,如果為0,則設為80
注:更多精彩文章請關注三聯編程教程欄目。