1、C#截取图片的方法
方法一、
一个像素一个像素的画,遍历每一个像素,速度慢
/// <summary>
/// 截取一张图片的制定部分
/// </summary>
/// <param name="bitmapPathAndName">原始图片路径名称</param>
/// <param name="width">截取图片的宽度</param>
/// <param name="height">截取图片的高度</param>
/// <param name="offsetX">开始截取图片的X坐标</param>
/// <param name="offsetY">开始截取图片的Y坐标</param>
/// <returns></returns>
public Bitmap GetPartOfImage(string bitmapPahtAndName, int width, int height, int offsetX, int offsetY)
{
Bitmap sourceBitmap = new Bitmap(bitmapPahtAndName);
Bitmap resultBitmap = new Bitmap(width, height);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (offsetX + x < sourceBitmap.Size.Width & offsetY + y < sourceBitmap.Size.Height)
{
resultBitmap.SetPixel(x, y, sourceBitmap.GetPixel(offsetX + x, offsetY + y));
}
}
}
return resultBitmap;
}
方法二、在一个知道位置画一个要截取的图像
/// <summary>
/// 截取一张图片的制定部分
/// </summary>
/// <param name="bitmapPathAndName">原始图片路径名称</param>
/// <param name="width">截取图片的宽度</param>
/// <param name="height">截取图片的高度</param>
/// <param name="offsetX">开始截取图片的X坐标</param>
/// <param name="offsetY">开始截取图片的Y坐标</param>
/// <returns></returns>
public Bitmap GetPartOfImageRec(string bitmapPathAndName, int width, int height, int offsetX, int offsetY)
{
Bitmap sourceBitmap = new Bitmap(bitmapPathAndName);
Bitmap resultBitmap = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(resultBitmap))
{
Rectangle resultRectangle = new Rectangle(0,0,width,height);
Rectangle sourceRectangle = new Rectangle(0 + offsetX, 0 + offsetY, width, height);
g.DrawImage(sourceBitmap, resultRectangle, sourceRectangle, GraphicsUnit.Pixel);
}
return resultBitmap;
}