C# 테크닉 - 스크린 캡쳐 (Bitmap)
# 현재 모니터 화면에서 특정한 영역의 정보를 이미지 파일로 저장
> Bitmap 형태를 이용
# WPF 에서 Bitmap 을 기본으로 제공하지 않기에 참조에서 dll 을 추가한다.
> 솔루션에서 참조 마우스 오른쪽 "참조 추가" 선택
# 소스 코드
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Drawing.Imaging;
public class ScreenCapture
{
BitmapImage m_bitmapimage = new BitmapImage();
public void CaptureFullscreen()
{
// 주화면의 크기 정보 읽기
int destx = (int)SystemParameters.PrimaryScreenWidth;
int desty = (int)SystemParameters.PrimaryScreenHeight;
CaptureROI(0, 0, destx, desty);
}
public void CaptureROI(int srcX, int srcY, int dstX, int dstY)
{
// 화면 크기만큼의 Bitmap 생성
int sizeX = dstX - srcX;
int sizeY = dstY - srcY;
Bitmap bmp = new Bitmap(sizeX, sizeY, PixelFormat.Format32bppArgb);
// Bitmap 이미지 변경을 위해 Graphics 객체 생성
Graphics gr = Graphics.FromImage(bmp);
// 화면을 그대로 카피해서 Bitmap 메모리에 저장
gr.CopyFromScreen(srcX, srcY, 0, 0, bmp.Size);
MemoryStream memory = new MemoryStream();
bmp.Save(memory, ImageFormat.Bmp);
memory.Position = 0;
m_bitmapimage = new BitmapImage();
m_bitmapimage.BeginInit();
m_bitmapimage.StreamSource = memory;
m_bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
m_bitmapimage.EndInit();
}
public void CaptureSave(string path)
{
Bitmap bmp = new Bitmap(m_bitmapimage.StreamSource);
bmp.Save(path);
}
}