C# 图片生成缩略图

C# 图片生成缩略图方法:

 1 /// <summary>
 2 /// 生成缩略图
 3 /// </summary>
 4 /// <param name="fileName">原图路径</param>
 5 /// <param name="newFile">缩略图路径</param>
 6 /// <param name="maxHeight">最大高度</param>
 7 /// <param name="maxWidth">最大宽度</param>
 8 public string ThumbnailImage(string fileName, string newFile, int maxHeight, int maxWidth)
 9 {
10     System.Drawing.Image img = System.Drawing.Image.FromFile(fileName);
11     System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;
12     //缩略图尺寸
13     double w = 0.0;                              //图片的宽
14     double h = 0.0;                              //图片的高
15     double sw = Convert.ToDouble(img.Width);
16     double sh = Convert.ToDouble(img.Height);
17     double mw = Convert.ToDouble(maxWidth);
18     double mh = Convert.ToDouble(maxHeight);
19     if (sw < mw && sh < mh)
20     {
21         w = sw;
22         h = sh;
23     }
24     else if ((sw / sh) > (mw / mh))
25     {
26         w = maxWidth;
27         h = (w * sh) / sw;
28     }
29     else
30     {
31         h = maxHeight;
32         w = (h * sw) / sh;
33     }
34     Size newSize = new Size(Convert.ToInt32(w), Convert.ToInt32(h));
35     Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
36     Graphics g = Graphics.FromImage(outBmp);
37     //设置画布的描绘质量
38     g.CompositingQuality = CompositingQuality.HighQuality;
39     g.SmoothingMode = SmoothingMode.HighQuality;
40     g.InterpolationMode = InterpolationMode.HighQualityBicubic;
41     g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
42     g.Dispose();
43     //以下代码为保存图片时,设置压缩质量
44     EncoderParameters encoderParams = new EncoderParameters();
45     long[] quality = new long[1];
46     quality[0] = 100;
47     EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
48     encoderParams.Param[0] = encoderParam;
49     //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
50     ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
51     ImageCodecInfo jpegICI = null;
52     for (int x = 0; x < arrayICI.Length;x++)
53     {
54         if (arrayICI[x].FormatDescription.Equals("JPEG"))
55         {
56             jpegICI = arrayICI[x];
57             //设置JPEG编码
58             break;
59         }
60      }
61      if (jpegICI != null)
62      {
63          Bitmap newbit = new Bitmap(outBmp);
64          newbit.Save(newFile, jpegICI, encoderParams);
65      }
66      else
67      {
68          outBmp.Save(newFile,
69          thisFormat);
70      }
71      img.Dispose();
72      outBmp.Dispose();
73      return newFile;
74 }

 

posted @ 2018-01-31 14:45  DotNet码农  阅读(534)  评论(0编辑  收藏
/*粒子线条,鼠标移动会以鼠标为中心吸附的特效*/