如何将 BitmapImage 从内存保存到 WPF C# 中的文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35804375/
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-13 13:42:06  来源:igfitidea点击:

How do I save a BitmapImage from memory into a file in WPF C#?

c#wpfsavebitmapimage

提问by Chris

I can't find anything over this and need some help. I have loaded a bunch of images into memory as BitmapImage types, so that I can delete the temp directory that they were stored in. I have successfully done this part. Now I need to save the images to a different temp location and I can't figure out how to do this The images are contained in a:

我在这方面找不到任何东西,需要一些帮助。我已经将一堆图像作为 BitmapImage 类型加载到内存中,以便我可以删除存储它们的临时目录。我已经成功地完成了这部分。现在我需要将图像保存到不同的临时位置,但我不知道如何做到这一点图像包含在:

Dictionary<string, BitmapImage>

The string is the filename. How do I save this collection to the new temp location? Thanks for any help!

字符串是文件名。如何将此集合保存到新的临时位置?谢谢你的帮助!

回答by Jay T

You need to use an encoder to save the image. The PngBitmapEncoder will handle most of the common image types (PNG, BMP, TIFF, etc). The following will take the image and save it:

您需要使用编码器来保存图像。PngBitmapEncoder 将处理大多数常见的图像类型(PNG、BMP、TIFF 等)。以下将拍摄图像并保存:

BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));

using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
{
    encoder.Save(fileStream);
}

I usually will write this into an extension method since it's a pretty common function for image processing/manipulating applications, such as:

我通常会将其写入扩展方法中,因为它是图像处理/操作应用程序的一个非常常见的功能,例如:

public static void Save(this BitmapImage image, string filePath)
{
    BitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(image));

    using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
    {
        encoder.Save(fileStream);
    }
}

This way you can just call it from the instances of the BitmapImage objects.

这样您就可以从 BitmapImage 对象的实例中调用它。