欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现缩放和剪裁图片的方法示例

程序员文章站 2023-11-26 23:36:10
本文实例讲述了c#实现缩放和剪裁图片的方法。分享给大家供大家参考,具体如下: using system; using system.collections.ge...

本文实例讲述了c#实现缩放和剪裁图片的方法。分享给大家供大家参考,具体如下:

using system;
using system.collections.generic;
using system.text;
using system.drawing;
using system.drawing.drawing2d;
using system.drawing.imaging;
namespace project
{
  class imageoperation
  {
    /// <summary>
    /// resize图片
    /// </summary>
    /// <param name="bmp">原始bitmap </param>
    /// <param name="neww">新的宽度</param>
    /// <param name="newh">新的高度</param>
    /// <param name="mode">保留着,暂时未用</param>
    /// <returns>处理以后的图片</returns>
    public static bitmap resizeimage(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;
      }
    }
    /// <summary>
    /// 剪裁 -- 用gdi+
    /// </summary>
    /// <param name="b">原始bitmap</param>
    /// <param name="startx">开始坐标x</param>
    /// <param name="starty">开始坐标y</param>
    /// <param name="iwidth">宽度</param>
    /// <param name="iheight">高度</param>
    /// <returns>剪裁后的bitmap</returns>
    public static bitmap cut(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;
      }
    }
  }
}

目标其实都是new rectangle(0, 0, iwidth, iheight),缩放算法把整个原始图都往目标区域里塞new rectangle(0, 0, bmp.width, bmp.height),而剪裁只是把原始区域上等宽等高的那个区域new rectangle(startx, starty, iwidth, iheight)1:1的塞到目标区域里。

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#图片操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。