[WPF] Control to Image

WPF 2021. 12. 14. 18:23
728x90
반응형
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WpfApp4
{
    public class Function
    {
        /// <summary>
        /// Grid를 Bitmap이미지로 변환
        /// </summary>
        /// <param name="grid">이미지 변환 할 Grid</param>
        /// <param name="filePath">저장될 png 파일 경로</param>
        /// <returns></returns>
        public static void SaveControlToImage(FrameworkElement grid, string filePath)
        {
            Size size = new Size(grid.ActualWidth, grid.ActualHeight);

            if (!size.IsEmpty)
            {
                RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);

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

                result.Render(drawingvisual);

                FileStream stream = new FileStream(filePath, FileMode.Create);

                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(result));

                encoder.Save(stream);

                stream.Close();
            }
        }
    }
}
반응형
Posted by kjun

댓글을 달아 주세요