WPF将UI保存为图片和保存位图
WPF将Ui保存为图片
private void SaveWindowContent(Window source, string fileName)
{
FrameworkElement elem = source.Content as FrameworkElement;
RenderTargetBitmap targetBitmap = new RenderTargetBitmap(
(int)elem.ActualWidth,
(int)elem.ActualHeight,
96d,
96d,
PixelFormats.Default);
targetBitmap.Render(source);
BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
// save file to disk
using (FileStream fs = File.Open(fileName, FileMode.OpenOrCreate))
{
encoder.Save(fs);
}
}
调用:
SaveWindowContent(this, "c:\tmp.bmp");
保存位图
private void btnSave_Click(object sender, RoutedEventArgs e)
{
//img 为你的图片控件
if (img.Source != null) {
SaveFileDialog op = new SaveFileDialog();
op.Filter = "JPEG Files(*.jpg)|*.jpg|BMP Files (*.bmp)|*.bmp";
if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
BitmapImage bmp = img.Source as BitmapImage;
BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
// save file to disk
using (FileStream fs = File.Open(op.FileName, FileMode.OpenOrCreate))
{
encoder.Save(fs);
}
}
}
}
原文:https://www.cnblogs.com/wgscd/articles/4918991.html
Winform保存窗体或者控件为图片:
Bitmap bit=new Bitmap(this.Width,this.Height);//实例化一个和窗体一样大的bitmap
Graphics g=Graphics.FromImage(bit);
g.CompositingQuality = CompositingQuality.HighQuality;//质量设为最高
g.CopyFromScreen(this.Left,this.Top,0,0,new Size(this.Width,this.Height));//保存整个窗体为图片
//g.CopyFromScreen(panel.PointToScreen(Point.Empty), Point.Empty, panel.Size);//只保存某个控件(这里是panel)
bit.Save("panel.png");//默认保存格式为PNG,保存成jpg格式质量不是很好