簡體   English   中英

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

字符串是名稱,例如,當該人想要添加圖像時,他們單擊顯示選擇圖像的按鈕,然后將pitcurebox設置為打開的圖像,然后當他們單擊一個顯示以下內容的按鈕時,出現一個文本框添加圖像,它將執行此images.Add(textBox1.Text,pictureBox1.Image)然后我要保存所有添加到文件夾的圖像

我已經在互聯網上尋找了這個問題,但是沒有人能為我提供答案,而且我真的很困,在此先感謝。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM