WPF learning 06: the content of the conversion control is pictures that can be stored, and the wpf control
In graphics software, we often use the "Save As image" function. This article describes how to convert the display content of the WPF control to an image.
Example
Save the displayed content as an image:
Code:
var bitmapRender = new RenderTargetBitmap((int)MainCanvas.ActualWidth, (int)MainCanvas.ActualHeight, 96, 96, PixelFormats.Pbgra32);bitmapRender.Render(MainCanvas);var bmpEncoder = new BmpBitmapEncoder();bmpEncoder.Frames.Add(BitmapFrame.Create(bitmapRender));using (var file = File.Create("output.bmp")) bmpEncoder.Save(file);
Convert images in various formats
Encapsulate the following functions:
Private void GetPicFromControl (FrameworkElement element, String type, String outputPath) {// 96 is the display DPI var bitmapRender = new RenderTargetBitmap (int) element. actualWidth, (int) element. actualHeight, 96, 96, PixelFormats. pbgra32); // control Content Rendering RenderTargetBitmap bitmapRender. render (element); BitmapEncoder encoder = null; // select the encoder switch (type. toUpper () {case "BMP": encoder = new BMP mapencoder (); break; Case "GIF": encoder = new GifBitmapEncoder (); break; case "JPEG": encoder = new JpegBitmapEncoder (); break; case "PNG": encoder = new PngBitmapEncoder (); break; case "TIFF": encoder = new TiffBitmapEncoder (); break; default: break;} // for general images, there is only one frame, and dynamic images have multiple frames. Encoder. Frames. Add (BitmapFrame. Create (bitmapRender); if (! Directory. exists (System. IO. path. getDirectoryName (outputPath) Directory. createDirectory (System. IO. path. getDirectoryName (outputPath); using (var file = File. create (outputPath) encoder. save (file );}
In WPF, controls are basically inherited from FrameworkElement. Therefore, all controls can be directly lost and converted to images in a specific format.
Test code XAML section:
<Window x:Class="BMPGenerator.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"> <StackPanel> <Canvas Name="MainCanvas" Background="White" Height="270"/> <Button Click="Button_Click">PicGenerate</Button> </StackPanel></Window>
Test code Background:
private void Button_Click(object sender, RoutedEventArgs e){ GetPicFromControl(MainCanvas, "BMP", @"E:\Tmp\output.BMP"); GetPicFromControl(MainCanvas, "GIF", @"E:\Tmp\output.GIF"); GetPicFromControl(MainCanvas, "JPEG", @"E:\Tmp\output.JPEG"); GetPicFromControl(MainCanvas, "PNG", @"E:\Tmp\output.PNG"); GetPicFromControl(MainCanvas, "TIFF", @"E:\Tmp\output.TIFF");}
Result: