c# -如何从字典<字符串中保存图像到一个文件夹

本文关键字:图像 文件夹 一个 保存 字典 字符串 | 更新日期: 2023-09-27 17:54:11

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

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

字符串是名称,例如当用户想要添加图像时他们点击一个按钮选择图像然后一个pitcurebox会被设置为打开的图像,然后有一个文本框,当他们点击一个按钮添加图像时,它会这样做images。add (textBox1。Text, pictureBox1.Image)然后我想把添加的所有图像保存到文件夹

我在网上找遍了这个问题,但是没有人能给我一个答案,我真的被卡住了,提前谢谢。

c# -如何从字典<字符串中保存图像到一个文件夹

Image类有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);
}

使用BinaryFormatter将图像保存到单个文件夹以序列化/反序列化您的字典到文件,如下所示:

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