C#實(shí)現(xiàn)縮放和剪裁圖片的方法示例
本文實(shí)例講述了C#實(shí)現(xiàn)縮放和剪裁圖片的方法。分享給大家供大家參考,具體如下:
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);
// 插值算法的質(zhì)量
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">開始坐標(biāo)X</param>
/// <param name="StartY">開始坐標(biāo)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;
}
}
}
}
目標(biāo)其實(shí)都是new Rectangle(0, 0, iWidth, iHeight),縮放算法把整個原始圖都往目標(biāo)區(qū)域里塞new Rectangle(0, 0, bmp.Width, bmp.Height),而剪裁只是把原始區(qū)域上等寬等高的那個區(qū)域new Rectangle(StartX, StartY, iWidth, iHeight)1:1的塞到目標(biāo)區(qū)域里。
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#圖片操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計入門教程》及《C#程序設(shè)計之線程使用技巧總結(jié)》
希望本文所述對大家C#程序設(shè)計有所幫助。
相關(guān)文章
WinFrom中l(wèi)abel背景透明的實(shí)現(xiàn)方法
這篇文章主要介紹了WinFrom中l(wèi)abel背景透明的實(shí)現(xiàn)方法,方法簡單實(shí)用,是C#程序設(shè)計中非常實(shí)用的技巧,需要的朋友可以參考下2014-09-09
.NET中保證線程安全的高級方法Interlocked類使用介紹
這篇文章主要介紹了.NET中保證線程安全的高級方法Interlocked類使用介紹,Interlocked類可以為為多個線程共享的變量提供原子操作,需要的朋友可以參考下2014-07-07
C# 無需COM組件創(chuàng)建快捷方式的實(shí)現(xiàn)代碼
做一個小程序, 需要創(chuàng)建快捷方式, 網(wǎng)上普遍的做法是引入 COM 組件, 雖然也挺方便的, 但引入之后, 程序就需要多帶一個 dll 文件, 這樣, 想做成單文件便攜版就不行了2011-05-05
C#實(shí)現(xiàn)IDisposable接口釋放非托管資源
這篇文章主要為大家介紹了C#實(shí)現(xiàn)IDisposable接口釋放非托管資源,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

