转载链接:https://blog.csdn.net/qq_43307934/article/details/87278138
//定义一个文件类型的枚举
public enum ImageFormat
{
JPG, BMP, PNG, GIF, TIF
}
//转为图片并保存
public void GenerateImage(BitmapSource bitmap, ImageFormat format, Stream destStream)
{
BitmapEncoder encoder = null;
switch (format)
{
case ImageFormat.JPG:
encoder = new JpegBitmapEncoder();
break;
case ImageFormat.PNG:
encoder = new PngBitmapEncoder();
break;
case ImageFormat.BMP:
encoder = new BmpBitmapEncoder();
break;
case ImageFormat.GIF:
encoder = new GifBitmapEncoder();
break;
case ImageFormat.TIF:
encoder = new TiffBitmapEncoder();
break;
default:
throw new InvalidOperationException();
}
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(destStream);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
RenderTargetBitmap rtb = new RenderTargetBitmap((int)this.Width, (int)this.Height, 96, 96, PixelFormats.Pbgra32);
rtb.Render(targetControl);
using (Stream fs = File.Create(@"E:\image.bmp"))
{
GenerateImage(rtb, ImageFormat.BMP, fs);
}
}
//保存为jpg和bmp的时候图片的背景是黑色的宽高即是窗体的宽高,png格式则为正常的控件内容大小及白色背景。