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

前端 未结 1 1281
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-20 18:10

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 sto

1条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 18:27

    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.

    0 讨论(0)
提交回复
热议问题