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
中国足彩网信息请查看IT技术专栏
2025国考·省考课程试听报名