天天看點

WPF将控件儲存成圖像

轉載連結:https://blog.csdn.net/qq_43307934/article/details/87278138

//定義一個檔案類型的枚舉
        public enum ImageFormat
        {
            JPG, BMP, PNG, GIF, TIF
        }
        //轉為圖檔并儲存
        public void GenerateImage(BitmapSource bitmap, ImageFormat format, Stream destStream)
        {
            BitmapEncoder encoder = null;

            switch (format)
            {
                case ImageFormat.JPG:
                    encoder = new JpegBitmapEncoder();
                    break;
                case ImageFormat.PNG:
                    encoder = new PngBitmapEncoder();
                    break;
                case ImageFormat.BMP:
                    encoder = new BmpBitmapEncoder();
                    break;
                case ImageFormat.GIF:
                    encoder = new GifBitmapEncoder();
                    break;
                case ImageFormat.TIF:
                    encoder = new TiffBitmapEncoder();
                    break;
                default:
                    throw new InvalidOperationException();
            }

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(destStream);
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
           RenderTargetBitmap rtb = new RenderTargetBitmap((int)this.Width, (int)this.Height, 96, 96, PixelFormats.Pbgra32);
            rtb.Render(targetControl);
 
            using (Stream fs = File.Create(@"E:\image.bmp"))
            {
                GenerateImage(rtb, ImageFormat.BMP, fs);
            }

        }
           

//儲存為jpg和bmp的時候圖檔的背景是黑色的寬高即是窗體的寬高,png格式則為正常的控件内容大小及白色背景。

WPF
上一篇: Efm32TG11B調試
下一篇: #dou

繼續閱讀