C# 无损图片压缩—— 基于Framework.40 类库兑现

C# 无损图片压缩—— 基于Framework.40 类库实现

分为两部分,一个是操作类,另外一个是测试。直接上代码了

 

一、测试代码

    private void button1_Click(object sender, EventArgs e)
    {
      string newSourcePath = ImgPath;//源图存放目录
      string newNewDir = MakePath;   //新图存放目录

      string sourceFile = Path.Combine(ImgPath, "app1.jpg"); //获取原图路径
      string newFile = string.Empty; //新图路径

      ImgThumbnail iz = new ImgThumbnail();
      Action<ImgThumbnail.ImgThumbnailType> Thumbnail = (type =>
        {
          //生成质量
          for (int i = 100; i >= 10; i -= 10)
          {
            //计算新图路径,测试命名:原图名_new_缩放类型_压缩质量.jpg
            newFile = Path.Combine(newNewDir, string.Format("app1_new_{1}_{0}.jpg", i, type.ToString()));
            //压缩图片
            iz.Thumbnail(sourceFile, newFile, 100, 100, i, type);
          }
        });
     
      Thumbnail(ImgThumbnail.ImgThumbnailType.Cut);//裁剪压缩(裁剪压缩还不好用,待调整!)
      Thumbnail(ImgThumbnail.ImgThumbnailType.H);  //以高度为参照压缩,不变形
      Thumbnail(ImgThumbnail.ImgThumbnailType.W);  //以宽度为参照压缩,不变形
      Thumbnail(ImgThumbnail.ImgThumbnailType.WH); //固定宽高压缩,变形
      MessageBox.Show("完成");
    }

 

 

二、操作类

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace MagickNet.App
{
  /// <summary>
  /// 图片压缩
  /// </summary>
  public class ImgThumbnail
  {
    /// <summary>
    /// 指定缩放类型
    /// </summary>
    public enum ImgThumbnailType
    {
      /// <summary>
      /// 指定高宽缩放(可能变形)
      /// </summary>
      WH = 0,
      /// <summary>
      /// 指定宽,高按比例
      /// </summary>
      W = 1,
      /// <summary>
      /// 指定高,宽按比例
      /// </summary>
      H = 2,
      /// <summary>
      /// 指定高宽裁减(不变形)
      /// </summary>
      Cut = 3
    }
    #region Thumbnail
    /// <summary>
    /// 无损压缩图片
    /// </summary>
    /// <param name="sFile">原图片</param>
    /// <param name="dFile">压缩后保存位置</param>
    /// <param name="height">高度</param>
    /// <param name="width"></param>
    /// <param name="flag">压缩质量 1-100</param>
    /// <param name="type">压缩缩放类型</param>
    /// <returns></returns>
    public bool Thumbnail(string sFile, string dFile, int height, int width, int flag, ImgThumbnailType type)
    {
      System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
      ImageFormat tFormat = iSource.RawFormat;

      //缩放后的宽度和高度
      int towidth = width;
      int toheight = height;
      //
      int x = 0;
      int y = 0;
      int ow = iSource.Width;
      int oh = iSource.Height;

      switch (type)
      {
        case ImgThumbnailType.WH://指定高宽缩放(可能变形)           
          {
            break;
          }
        case ImgThumbnailType.W://指定宽,高按比例     
          {
            toheight = iSource.Height * width / iSource.Width;
            break;
          }
        case ImgThumbnailType.H://指定高,宽按比例
          {
            towidth = iSource.Width * height / iSource.Height;
            break;
          }
        case ImgThumbnailType.Cut://指定高宽裁减(不变形)     
          {
            if ((double)iSource.Width / (double)iSource.Height > (double)towidth / (double)toheight)
            {
              oh = iSource.Height;
              ow = iSource.Height * towidth / toheight;
              y = 0;
              x = (iSource.Width - ow) / 2;
            }
            else
            {
              ow = iSource.Width;
              oh = iSource.Width * height / towidth;
              x = 0;
              y = (iSource.Height - oh) / 2;
            }
            break;
          }
        default:
          break;
      }

      Bitmap ob = new Bitmap(towidth, toheight);
      Graphics g = Graphics.FromImage(ob);
      g.Clear(System.Drawing.Color.WhiteSmoke);
      g.CompositingQuality = CompositingQuality.HighQuality;
      g.SmoothingMode = SmoothingMode.HighQuality;
      g.InterpolationMode = InterpolationMode.HighQualityBicubic;
      g.DrawImage(iSource
        , new Rectangle(x, y, towidth, toheight)
        , new Rectangle(0,0, iSource.Width, iSource.Height)
        , GraphicsUnit.Pixel);
      g.Dispose();
      //以下代码为保存图片时,设置压缩质量
      EncoderParameters ep = new EncoderParameters();     
      long[] qy = new long[1];
      qy[0] = flag;//设置压缩的比例1-100
      EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
      ep.Param[0] = eParam;
      try
      {
        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
        ImageCodecInfo jpegICIinfo = null;
        for (int i = 0; i < arrayICI.Length; i++)
        {
          if (arrayICI[i].FormatDescription.Equals("JPEG"))
          {
            jpegICIinfo = arrayICI[i];
            break;
          }
        }
        if (jpegICIinfo != null)
        {
          ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
        }
        else
        {
          ob.Save(dFile, tFormat);
        }
        return true;
      }
      catch
      {
        return false;
      }
      finally
      {
        iSource.Dispose();

        ob.Dispose();

      }
    }
    #endregion
  }
}

 

转载请保留:http://www.iqingcao.com