在图形软件中,我们经常使用到“另存为图片”的功能,本文即介绍如何将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);
转换各种格式的图片
封装出如下函数:
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部分:
<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>
测试代码后台部分:
private void Button_Click(object sender, RoutedEventArgs e) { GetPicFromControl(MainCanvas, "BMP", @"E:Tmpoutput.BMP"); GetPicFromControl(MainCanvas, "GIF", @"E:Tmpoutput.GIF"); GetPicFromControl(MainCanvas, "JPEG", @"E:Tmpoutput.JPEG"); GetPicFromControl(MainCanvas, "PNG", @"E:Tmpoutput.PNG"); GetPicFromControl(MainCanvas, "TIFF", @"E:Tmpoutput.TIFF"); }
结果: