17

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!

Chris
  • 363
  • 1
  • 4
  • 16
  • Is there a reason you aren't just moving the files? If the server or your program crashes before you write them back to disk, the data will be lost. If you just use IO to move the files, there is (effectively) no risk of data loss. – Tony Hinkle Mar 04 '16 at 19:28
  • Yes, I have a different method for handling recovering that I intend to implement. When a user loads a project file for my application (a zip file), it extracts it all to a temp directory, loads the files into memory, then cleans up that temp directory. The program will then periodically autosave the project in a backup file. When the user wants to then save their project, I want to unload all these resources in memory into a temp directory, zip that up as the project file, save it to the users location, then delete the temp directory. I just need to figure how to save from the memory. – Chris Mar 04 '16 at 19:36
  • Do you *only* load the images to memory, or do you also show them in a UI? If you don't show them, there is no need to create BitmapImages, you could simply store the binary file content as byte array. Anyway, saving a BitmapImage to file is done by a BitmapEncoder, e.g. a PngBitmapEncoder. – Clemens Mar 04 '16 at 19:42
  • I'll take a look into that. And yes, I show the images in the UI. – Chris Mar 04 '16 at 19:45

1 Answers1

46

You need to use an encoder to save the image. 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.

Clemens
  • 123,504
  • 12
  • 155
  • 268
Jay T
  • 853
  • 10
  • 11