原文地址:http://blog.sina.com.cn/s/blog_6427a6b50101el9d.html
在GDI+中,縮放和剪裁可以看作同一個操作,無非就是原始區域的選擇不同罷了。
///
/// Resize圖片
///
/// 原始Bitmap
/// 新的寬度
/// 新的高度
/// 保留着,暫時未用
/// 處理以后的圖片
public static Bitmap KiResizeImage(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 KiCut(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;
}
}
注意到區別g.DrawImage中第二個new Rectangle。目標其實都是new Rectangle(0, 0, iWidth, iHeight),縮放算法把整個原始圖都往目標區域里塞new Rectangle(0, 0, bmp.Width, bmp.Height),而剪裁只是把原始區域上等寬等高的那個區域new Rectangle(StartX, StartY, iWidth, iHeight)1:1的塞到目標區域里
打印相關內容:
圖片裁剪:http://blog.csdn.net/redder_xu/article/details/6760589
圖片像素相關:http://www.cnblogs.com/yjmyzz/archive/2012/01/09/2316892.html