如何将 WPF BitmapSource 图像保存到文件? [英] How to save a WPF BitmapSource image to a file?
问题描述
在 WPF 中,System.Windows.Clipboard.getImage()
函数返回一个 BitmapSource
对象.作为来自 WinForms 背景的 WPF 新手,我不清楚如何将此图像保存到文件中.我必须采取哪些步骤?
In WPF, the System.Windows.Clipboard.getImage()
function returns a BitmapSource
object. As a newbie in WPF coming from a WinForms background, its not clear to me how to save this image to a file. What are the steps I must take?
推荐答案
您需要使用编码器(BitmapEncoder
).例如,要将其保存为 PNG 格式,您可以执行以下操作:
You need to use an encoder (subclass of BitmapEncoder
). For instance, to save it to the PNG format, you do something like that :
public static void SaveClipboardImageToFile(string filePath)
{
var image = Clipboard.GetImage();
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(fileStream);
}
}
顺便说一下,请注意有 Clipboard.GetImage
中的一个错误.如果您只是将图像保存到文件中应该没有问题,但是如果您想显示它就会有问题.
By the way, note that there's a bug in Clipboard.GetImage
. It shouldn't be a problem if you just save the image to a file, but it will be if you want to display it.
上面提到的错误似乎已在 4.0 中修复
EDIT : the bug mentioned above seems to be fixed in 4.0
这篇关于如何将 WPF BitmapSource 图像保存到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!