C#中如何对图片进行缩放和剪裁

原创|其它|编辑:郝浩|2009-12-17 11:26:53.000|阅读 1232 次

概述:应听众点播要求,今天说说用C#做图片的缩放和剪裁,相信很多人会对这部分内容感兴趣,毕竟这个操作太实用了。

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

  应听众点播要求,今天说说用C#做图片的缩放和剪裁,相信很多人会对这部分内容感兴趣,毕竟这个操作太实用了。

  其实在GDI+中,缩放和剪裁可以看作同一个操作,无非就是原始区域的选择不同罢了。空口无凭,先看具体算法可能更好理解。

  /// Resize图片
  /// 
  /// 原始Bitmap
  /// 新的宽度
  /// 新的高度
  /// 保留着,暂时未用
  /// 处理以后的图片
  public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH, int Mode)
  {
  try
  {
  Bitmap b = new Bitmap(newW, newH);
  Graphics g = Graphics.FromImage(b);
  // 插值算法的质量
  g.IntERPolationMode = InterpolationMode.HighQualityBicubic;
  g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
  g.Dispose();
  return b;
  }
  catch
  {
  return null;
  }
  }
  // ===============================
  /// 
  /// 剪裁 -- 用GDI+
  /// 
  /// 原始Bitmap
  /// 开始坐标X
  /// 开始坐标Y
  /// 宽度
  /// 高度
  /// 剪裁后的Bitmap
  public static Bitmap KiCut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
  {
  if (b == null)
  {
  return null;
  }
  int w = b.Width;
  int h = b.Height;
  if (StartX >= w || StartY >= h)
  {
  return null;
  }
  if (StartX + iWidth > w)
  {
  iWidth = w - StartX;
  }
  if (StartY + iHeight > h)
  {
  iHeight = h - StartY;
  }
  try
  {
  Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
  Graphics g = Graphics.FromImage(bmpOut);
  g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
  g.Dispose();
  return bmpOut;
  }
  catch
  {
  return null;
  }
  }

  注意到区别了吗?提示,g.DrawImage中第二个new Rectangle。

  目标其实都是new Rectangle(0, 0, iWidth, iHeight),缩放算法把整个原始图都往目标区域里塞new Rectangle(0, 0, bmp.Width, bmp.Height),而剪裁只是把原始区域上等宽等高的那个区域new Rectangle(StartX, StartY, iWidth, iHeight)1:1的塞到目标区域里。很容易吧。


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:网络转载

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP