栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
  {
    /// 
    /// Resize图片
    /// 
    /// 原始Bitmap 
    /// 新的宽度
    /// 新的高度
    /// 保留着,暂时未用
    /// 处理以后的图片
    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;
      }
    }
    /// 
    /// 剪裁 -- 用GDI+
    /// 
    /// 原始Bitmap
    /// 开始坐标X
    /// 开始坐标Y
    /// 宽度
    /// 高度
    /// 剪裁后的Bitmap
    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#程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/123374.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号