本文實例講述了c#圖像截取的實現方法。分享給大家供大家參考。具體如下:
圖像截取的相關代碼如下:
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#程序設計有所幫助。
新聞熱點
疑難解答