C# - 如何将图像从字典 <string, images> 保存到文件夹

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

我目前正在开发 2D 游戏引擎,到目前为止我已经添加了加载和删除图像的功能,但现在我想保存它们,这是字典:

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

字符串是名称,例如,当人们想要添加图像时,他们单击一个显示“选择图像”的按钮,然后一个 picturebox 将被设置为打开的图像,然后有一个文本框,当他们单击一个显示添加图像的按钮,它会执行此操作 images.Add(textBox1.Text, pictureBox1.Image) 然后我想保存所有添加到文件夹的图像

我在网上找遍了这个,但没有人给我答案,我真的被困住了,在此先感谢。

使用 BinaryFormatter 将图像保存到单个文件夹到 serialize/deserialize 你的字典以这样的方式归档:

public void Save(string filename)
{
    var bin_formater = new BinaryFormatter();
    using (var stream = File.Create(filename))
    {
        bin_formater.Serialize(stream, images); //images is your dictionary
    }
}

Imageclass有Save方法。所以你可以这样做:

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

更新

如果你想使用字典中的字符串作为文件名,稍微改变上面的代码:

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