最开始的目的是保存控件为图片,然后保存到Excel中(Epplus库)。
- 控件保存成图片
// UI --> Png
public static void UISaveToPng(this FrameworkElement ui, string fileName)
{
int width = (int)ui.ActualWidth;
int height = (int)ui.ActualHeight;
RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);
bmp.Render(ui);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
FileStream fs = new FileStream(fileName, FileMode.Create);
encoder.Save(fs);
fs.Close();
}
- 转BitmapImage
int width = (int)grid2DMap.ActualWidth;
int height = (int)grid2DMap.ActualHeight;
RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);
bmp.Render(grid2DMap);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
BitmapImage bitmapImage = new BitmapImage();
using (var memoryStream = new MemoryStream())
{
encoder.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
}
- 转System.Drawing.Image
MemoryStream memoryStream = new MemoryStream();
encoder.Save(memoryStream);
System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);