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

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

我找不到任何相关信息,需要一些帮助。我已经将一堆图像作为 BitmapImage 类型加载到内存中,这样我就可以删除存储它们的临时目录。我已经成功完成了这一部分。现在我需要将图像保存到不同的临时位置,但我不知道该怎么做图像包含在:

Dictionary<string, BitmapImage>

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

您需要使用编码器来保存图像。以下将拍摄图像并保存:

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

我通常会将其写入扩展方法,因为它是图像 processing/manipulating 应用程序的一个非常常见的函数,例如:

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

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