[WPF] Grid를 Bitmap 이미지로 변환 후 저장하기

WPF의 Grid를 사용하여 사용자의 입력을 받는 문서를 작성하거나 여러 이미지를 가시화할 시, 이를 이미지로 저장하는 기능이 필요할 경우가 있습니다.

따라서 Grid 컨트롤을 하위 요소들과 함께 Bitmap으로 변환하고 이미지를 저장하는 방법에 대해 알아보겠습니다.

소스코드

먼저 Grid 컨트롤 내용들을 Bitmap으로 변환합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// <summary>
/// Grid를 Bitmap이미지로 변환
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static RenderTargetBitmap GetBitmapFromControl(FrameworkElement element)
{
Size size = new Size(element.ActualWidth, element.ActualHeight);
if (size.IsEmpty)
return null;

DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext context = drawingVisual.RenderOpen())
{
context.DrawRectangle(new VisualBrush(element), null, new Rect(new Point(), size));
context.Close();
}

RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);
result.Render(drawingVisual);

return result;
}

변환된 Bitmap을 PNG 또는 TIF 이미지 파일로 저장하는 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/// <summary>
/// Bitmap을 이미지로 저장
/// </summary>
/// <param name="bitmap"></param>
/// <param name="filePath">파일 경로</param>
public static void SaveImage(RenderTargetBitmap bitmap, string filePath)
{
string ext = System.IO.Path.GetExtension(filePath);

using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
if (ext == ".png")
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(stream);
}
else if (ext == ".tif")
{
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(stream);
}

stream.Close();
}
}

사용 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<Window x:Class="TestProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="800"
Height="600"
Title="이미지 저장하기">
<Grid Name="grid">
<Canvas>
...
</Canvas>
<StackPanel>
...
</StackPanel>
</Grid>
</Window>

GetBitmapFromControl 함수를 사용하여 이미지로 저장하려는 Grid를 Bitmap으로 변환합니다. 그리고 SaveImage 함수의 파라미터에 bitmap, 파일경로를 넣어 이미지를 저장합니다.

1
2
3
4
5
6
7
8
9
/// <summary>
/// 이미지 저장
/// </summary>
private void Capture()
{
RenderTargetBitmap bitmap = GetBitmapFromControl(this.grid);
string filePath = "d:\\test.png";
SaveImage(bitmap, filePath);
}

Grid 컨트롤 뿐만 아니라 FrameworkElement을 상속받는 모든 컨트롤들을 위의 함수를 사용하여 이미지를 저장할 수 있습니다.

Share