在圖形軟件中,咱們常用到「另存爲圖片」的功能,本文即介紹如何將WPF控件顯示內容轉換爲圖片。函數
保存界面顯示內容爲圖片:測試
代碼:編碼
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);
封裝出以下函數:spa
private void GetPicFromControl(FrameworkElement element, String type, String outputPath) { //96爲顯示器DPI var bitmapRender = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96, 96, PixelFormats.Pbgra32); //控件內容渲染RenderTargetBitmap bitmapRender.Render(element); BitmapEncoder encoder = null; //選取編碼器 switch (type.ToUpper()) { case "BMP": encoder = new BmpBitmapEncoder(); 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; } //對於通常的圖片,只有一幀,動態圖片是有多幀的。 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); }
測試代碼XAML部分:code
<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>
測試代碼後臺部分:orm
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"); }
結果:xml