如何将 WPF BitmapSource 图像保存到文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2900447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:47:49  来源:igfitidea点击:

How to save a WPF BitmapSource image to a file?

wpfbitmapsource

提问by tbischel

In WPF, the System.Windows.Clipboard.getImage()function returns a BitmapSourceobject. 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?

在 WPF 中,该System.Windows.Clipboard.getImage()函数返回一个BitmapSource对象。作为来自 WinForms 背景的 WPF 新手,我不清楚如何将此图像保存到文件中。我必须采取哪些步骤?

回答by Thomas Levesque

You need to use an encoder (subclass of BitmapEncoder). For instance, to save it to the PNG format, you do something like that :

您需要使用编码器( 的子类BitmapEncoder)。例如,要将其保存为 PNG 格式,您可以执行以下操作:

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);
    }
}

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.

顺便说一句,请注意,有一个错误Clipboard.GetImage。如果您只是将图像保存到文件中应该没有问题,但是如果您想显示它就会有问题。



EDIT : the bug mentioned above seems to be fixed in 4.0

编辑:上面提到的错误似乎已在 4.0 中修复