开发杂记:C#压缩JPG文件

by kevin 20. 八月 2013 21:44 >

最近在开发65emall的时候,发现产品的缩略图每个都有几十KB困惑,检查了下,发现,在生成缩略图的时候,代码里只是设置了InterpolationMode,如下

   1: g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;

其实这样的压缩,非常有限,所以文件还是非常大。

其实,要真正压缩jpg文件,还是要降低图片的质量,这里我们设置了50%,结果图片大小缩小了80-90%。

具体的代码如下

   1: private static ImageCodecInfo GetEncoder(ImageFormat format)
   2: {
   3:     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
   4:     foreach (ImageCodecInfo codec in codecs)
   5:     {
   6:         if (codec.FormatID == format.Guid)
   7:         {
   8:             return codec;
   9:         }
  10:     }
  11:     return null;
  12: }
  13:  
  14: private static void CreateImage(int oldWidth, int oldHeight, int limitWidth, int limitHeight,
  15:                                        System.Drawing.Image oldImage, string path, string fileName)
  16:    {
  17:        if (!System.IO.Directory.Exists(path))
  18:        {
  19:            System.IO.Directory.CreateDirectory(path);
  20:        }
  21:        int createWidth, createHeight;
  22:        ImageSize(oldWidth, oldHeight, limitWidth, limitHeight, out createWidth, out createHeight);
  23:  
  24:        System.Drawing.Bitmap createImage = new System.Drawing.Bitmap(createWidth, createHeight);
  25:        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(createImage);
  26:        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
  27:        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  28:        g.Clear(System.Drawing.Color.Transparent);
  29:        g.DrawImage(oldImage, new System.Drawing.Rectangle(0, 0, createWidth, createHeight),
  30:                    new System.Drawing.Rectangle(0, 0, oldImage.Width, oldImage.Height),
  31:                    System.Drawing.GraphicsUnit.Pixel);
  32:        ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
  33:        System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
  34:        EncoderParameters myEncoderParameters = new EncoderParameters(1);
  35:        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
  36:        myEncoderParameters.Param[0] = myEncoderParameter;
  37:        createImage.Save(path + fileName, jgpEncoder, myEncoderParameters);
  38:        g.Dispose();
  39:        createImage.Dispose();
  40:    }

参考资料:

How to: Set JPEG Compression Level

How to: Use Interpolation Mode to Control Image Quality During Scaling

分享到: 更多