c#如何分割图片并展示原图中一部分picturebox1中打开了一副图像,现在的话,在picturebox1中选取了两个点(x0,y0)以及(x1,y1).如何在picturebox2中绘制坐标x0~x2,y0~y1这部分的图像?代码的话又该怎么写呢?那么如何将改部分的图像在picturebox2中显示呢?下面代码的在运行时会报错,错误为:pictureBox2.Image = bmSmall;这一句未将对象引用设置到对象的实例.Rectangle rect = new Rectangle(x0,y0,(
2019-04-13
c#如何分割图片并展示原图中一部分
picturebox1中打开了一副图像,现在的话,在picturebox1中选取了两个点(x0,y0)以及(x1,y1).如何在picturebox2中绘制坐标x0~x2,y0~y1这部分的图像?代码的话又该怎么写呢?
那么如何将改部分的图像在picturebox2中显示呢?下面代码的在运行时会报错,错误为:pictureBox2.Image =
bmSmall;这一句
未将对象引用设置到对象的实例.
Rectangle rect = new Rectangle(x0,y0,(x1-x0),(y1-y0));
Bitmap bmSmall = new Bitmap(rect.Width,rect.Height,
System.Drawing.Imaging.PixelFormat.Format32bppRgb);
using
(Graphics grSmall = Graphics.FromImage(bmSmall))
{
grSmall.DrawImage(pictureBox1.Image,new
System.Drawing.Rectangle(0,0,bmSmall.Width,bmSmall.Height),rect,
GraphicsUnit.Pixel);
grSmall.Dispose();
pictureBox2.Image =
bmSmall;
}
优质解答
根据两个点(x0,y0)以及(x1,y1)得出一个区域Rectangle
Rectangle rect = new Rectangle (x0,y0,(x1-x0),(y1-y0));
再调用如下的函数可得到截取的图像
///
/// 截取图像的矩形区域
///
/// 源图像对应picturebox1
/// 矩形区域,如上初始化的rect
/// 矩形区域的图像
public static Image AcquireRectangleImage(Image source, Rectangle rect) {
if (source == null || rect.IsEmpty) return null;
Bitmap bmSmall = new Bitmap(rect.Width, rect.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
//Bitmap bmSmall = new Bitmap(rect.Width, rect.Height, source.PixelFormat);
using (Graphics grSmall = Graphics.FromImage(bmSmall)) {
grSmall.DrawImage(source,
new System.Drawing.Rectangle(0, 0, bmSmall.Width, bmSmall.Height),
rect,
GraphicsUnit.Pixel);
grSmall.Dispose();
}
return bmSmall;
}
根据两个点(x0,y0)以及(x1,y1)得出一个区域Rectangle
Rectangle rect = new Rectangle (x0,y0,(x1-x0),(y1-y0));
再调用如下的函数可得到截取的图像
///
/// 截取图像的矩形区域
///
/// 源图像对应picturebox1
/// 矩形区域,如上初始化的rect
/// 矩形区域的图像
public static Image AcquireRectangleImage(Image source, Rectangle rect) {
if (source == null || rect.IsEmpty) return null;
Bitmap bmSmall = new Bitmap(rect.Width, rect.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
//Bitmap bmSmall = new Bitmap(rect.Width, rect.Height, source.PixelFormat);
using (Graphics grSmall = Graphics.FromImage(bmSmall)) {
grSmall.DrawImage(source,
new System.Drawing.Rectangle(0, 0, bmSmall.Width, bmSmall.Height),
rect,
GraphicsUnit.Pixel);
grSmall.Dispose();
}
return bmSmall;
}