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

牧云@^-^@ 提交于 2020-01-02 02:37:07

问题


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:

Dictionary<string, BitmapImage>

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


回答1:


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:

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.



来源:https://stackoverflow.com/questions/35804375/how-do-i-save-a-bitmapimage-from-memory-into-a-file-in-wpf-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!