Search code examples
c#dictionarygame-engine

C# - How to save images from a dictionary<string, images> to a folder


I am currently working on a 2D Game Engine, so far I have added a feature to load and remove images, but now I want to save them, this is the dictionary:

public Dictionary<string, Image> images = new Dictionary<string, Image>();

The string is the name, for example when the person wants to add an image they click a button that says choose image then a pitcurebox will be set as the image that was opened, then there is a textbox, when they click a button that says Add Image, it will do this images.Add(textBox1.Text, pictureBox1.Image) Then I want to save all the images added to a folder

I have looked all over the internet for this, but no one has an answer for me, and I'm really stuck, thanks in advance.


Solution

  • The Image class has the Save method. So you could do something like this:

    foreach (var imgX in images.Select(kvp => kvp.Value))
    {
        imgX.Save("figure_a_file_path_and_name", ImageFormat.Jpeg);
    }
    

    UPDATE

    If you would like to use the string in the dictionary as file name change the above code a little bit:

    var folder = "figure_the_folder_path\\";
    
    foreach (var entry in images)
    {
        var destinationFile = string.Concat(folder, entry.Key); 
        var img = entry.Value;
        img.Save(destinationFile, ImageFormat.Jpeg);
    }