C#实现缩放和剪裁图片的方法示例
本文实例讲述了C#实现缩放和剪裁图片的方法。分享给大家供大家参考,具体如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Drawing;
usingSystem.Drawing.Drawing2D;
usingSystem.Drawing.Imaging;
namespaceProject
{
classImageOperation
{
///
///Resize图片
///
///原始Bitmap
///新的宽度
///新的高度
///保留着,暂时未用
///处理以后的图片
publicstaticBitmapResizeImage(Bitmapbmp,intnewW,intnewH,intMode)
{
try
{
Bitmapb=newBitmap(newW,newH);
Graphicsg=Graphics.FromImage(b);
//插值算法的质量
g.InterpolationMode=InterpolationMode.HighQualityBicubic;
g.DrawImage(bmp,newRectangle(0,0,newW,newH),newRectangle(0,0,bmp.Width,bmp.Height),GraphicsUnit.Pixel);
g.Dispose();
returnb;
}
catch
{
returnnull;
}
}
///
///剪裁--用GDI+
///
///原始Bitmap
///开始坐标X
///开始坐标Y
///宽度
///高度
///剪裁后的Bitmap
publicstaticBitmapCut(Bitmapb,intStartX,intStartY,intiWidth,intiHeight)
{
if(b==null)
{
returnnull;
}
intw=b.Width;
inth=b.Height;
if(StartX>=w||StartY>=h)
{
returnnull;
}
if(StartX+iWidth>w)
{
iWidth=w-StartX;
}
if(StartY+iHeight>h)
{
iHeight=h-StartY;
}
try
{
BitmapbmpOut=newBitmap(iWidth,iHeight,PixelFormat.Format24bppRgb);
Graphicsg=Graphics.FromImage(bmpOut);
g.DrawImage(b,newRectangle(0,0,iWidth,iHeight),newRectangle(StartX,StartY,iWidth,iHeight),GraphicsUnit.Pixel);
g.Dispose();
returnbmpOut;
}
catch
{
returnnull;
}
}
}
}
目标其实都是newRectangle(0,0,iWidth,iHeight),缩放算法把整个原始图都往目标区域里塞newRectangle(0,0,bmp.Width,bmp.Height),而剪裁只是把原始区域上等宽等高的那个区域newRectangle(StartX,StartY,iWidth,iHeight)1:1的塞到目标区域里。
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#图片操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》
希望本文所述对大家C#程序设计有所帮助。