C#中:将多幅图片保存到一个文件 [英] C#: Save multiple images to a single file

查看:1082
本文介绍了C#中:将多幅图片保存到一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作维持图像的字典类。
这本词典应保存并从文件加载。

I am working on a class that maintains a dictionary of images. This dictionary should be saved to and loaded from a file.

我实现了以下解决方案,但问题是,根据用于Image.FromStream MSDN
文档();结果
的http:// MSDN .microsoft.com / EN-US /库/ 93z9ee4x(v = VS.80)的.aspx 结果

I implemented the below solution, but the problem is that according to MSDN documentation for Image.FromStream();
http://msdn.microsoft.com/en-us/library/93z9ee4x(v=VS.80).aspx

流重置为零如果此方法用相同的流连续调用。

"The stream is reset to zero if this method is called successively with the same stream."

任何想法如何解决这一问题? 。载入字典的速度是至关重要的。

Any ideas how to fix this? The speed of loading the dictionary is critical.

class ImageDictionary
{
    private Dictionary<string, Image> dict = new Dictionary<string, Image>();

    public void AddImage(string resourceName, string filename)
    {
       //...
    }

    public Image GetImage(string resourceName) 
    {
       //...
    }


    public void Save(string filename)
    {
        var stream = new FileStream(filename, FileMode.Create);
        var writer = new BinaryWriter(stream);
        writer.Write((Int32) dict.Count);
        foreach (string key in dict.Keys)
        {
            writer.Write(key);

            Image img;
            dict.TryGetValue(key, out img);
            img.Save(stream,System.Drawing.Imaging.ImageFormat.Png);
        }
        writer.Close();
        stream.Close();
    }

    public void Load(string filename)
    {
        var stream = new FileStream(filename, FileMode.Open);
        var reader = new BinaryReader(stream);
        Int32 count = reader.ReadInt32();
        dict.Clear();

        for (int i = 0; i < count; i++)
        {
            string key = reader.ReadString();
            Image img = Image.FromStream(stream);
            dict.Add(key, img);

        }

        reader.Close();
        stream.Close();

    }



}


推荐答案

Image.FromStream 方法需要一个有效的图像流。你是串连多个图像到一个文件,如果你想重建他们还需要保存它们的大小除了自己的号码。一个更容易的解决办法是简单的二进制序列化图像词典:

The Image.FromStream method expects a valid image stream. You are concatenating multiple images into a single file and if you want to reconstruct them you will also need to save their size in addition to their number. An easier solution would be to simply binary serialize the image dictionary:

public void Save(string filename)
{
    var serializer = new BinaryFormatter();
    using (var stream = File.Create(filename))
    {
        serializer.Serialize(stream, dict);
    }
}

public void Load(string filename)
{
    var serializer = new BinaryFormatter();
    using (var stream = File.Open(filename, FileMode.Open))
    {
        dict = (Dictionary<string, Image>)serializer.Deserialize(stream);
    }
}

这篇关于C#中:将多幅图片保存到一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆