c#图像截取实例
本文实例讲述了c#图像截取的实现方法。分享给大家供大家参考。具体如下:
图像截取的相关代码如下:
{
initializecomponent();
}
private void button1_click(object sender, eventargs e)
{
image pic = new bitmap(this.width, this.height);
graphics graphic = graphics.fromimage(pic);
graphic.copyfromscreen(new point(this.location.x, this.location.y), new point(0, 0), new size(this.width, this.height));
pic.save(@"d:/test.jpeg", imageformat.jpeg);
graphic.dispose();
}
[system.runtime.interopservices.dllimportattribute("gdi32.dll")]
private static extern bool bitblt(
intptr hdcdest, //目标设备的句柄
int nxdest, // 目标对象的左上角的x坐标
int nydest, // 目标对象的左上角的x坐标
int nwidth, // 目标对象的矩形的宽度
int nheight, // 目标对象的矩形的长度
intptr hdcsrc, // 源设备的句柄
int nxsrc, // 源对象的左上角的x坐标
int nysrc, // 源对象的左上角的x坐标
system.int32 dwrop // 光栅的操作值
);
[system.runtime.interopservices.dllimportattribute("gdi32.dll")]
private static extern intptr createdc(
string lpszdriver, // 驱动名称
string lpszdevice, // 设备名称
string lpszoutput, // 无用,可以设定位"null"
intptr lpinitdata // 任意的打印机数据
);
private void form1_sizechanged(object sender, eventargs e)
{
}
private void button2_click(object sender, eventargs e)
{
this.hide();
intptr dc1 = createdc("display", null,
null, (intptr)null);
//创建显示器的dc
graphics g1 = graphics.fromhdc(dc1);
//由一个指定设备的句柄创建一个新的graphics对象
bitmap myimage =
new bitmap(screen.primaryscreen.bounds.width,
screen.primaryscreen.bounds.height, g1);
//根据屏幕大小创建一个与之相同大小的bitmap对象
graphics g2 = graphics.fromimage(myimage);
//获得屏幕的句柄
intptr dc3 = g1.gethdc();
//获得位图的句柄
intptr dc2 = g2.gethdc();
//把当前屏幕捕获到位图对象中
bitblt(dc2, 0, 0, screen.primaryscreen.bounds.width,
screen.primaryscreen.bounds.height,
dc3, 0, 0, 13369376);
//把当前屏幕拷贝到位图中
g1.releasehdc(dc3);
//释放屏幕句柄
g2.releasehdc(dc2);
//释放位图句柄
bitmap img = new bitmap(myimage, 800, 600);
//缩放图片到800*600
img.save("d:\\myjpeg.jpg", imageformat.jpeg);
messagebox.show("已经把当前屏幕保存到" +
"c:\\myjpeg.jpg文件中!");
this.show();
}
希望本文所述对大家的c#程序设计有所帮助。