源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-08-23 11:24 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#实现缩放和剪裁图片的方法示例
本文实例讲述了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;
      }
    }
  }
}

目标其实都是[code]new Rectangle(0, 0, iWidth, iHeight)[/code],缩放算法把整个原始图都往目标区域里塞[code]new Rectangle(0, 0, bmp.Width, bmp.Height)[/code],而剪裁只是把原始区域上等宽等高的那个区域new Rectangle(StartX, StartY, iWidth, iHeight)1:1的塞到目标区域里。 更多关于C#相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/274.htm]C#图片操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/165.htm]C#常见控件用法教程[/url]》、《[url=http://www.1sucai.cn/Special/125.htm]WinForm控件用法总结[/url]》、《[url=http://www.1sucai.cn/Special/116.htm]C#数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/478.htm]C#面向对象程序设计入门教程[/url]》及《[url=http://www.1sucai.cn/Special/227.htm]C#程序设计之线程使用技巧总结[/url]》 希望本文所述对大家C#程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部