微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – BinaryFormatter.Serialize(Image) – ExternalException – GDI中发生一般错误

当我尝试使用BinaryFormatter序列化一些图像时,我会得到一个ExternalException – GDI中发生了一般性错误.“经过一段时间的努力,我决定创建一个简单的测试项目来缩小问题范围:

static void Main(string[] args)
    {
        string file = @"C:\temp\delme.jpg";

        //Image i = new Bitmap(file);
        //using(FileStream fs = new FileStream(file,FileMode.Open,FileAccess.Read))

        byte[] data = File.ReadAllBytes(file);
        using(MemoryStream originalms = new MemoryStream(data))
        {
            using (Image i = Image.FromStream(originalms))
            {
                BinaryFormatter bf = new BinaryFormatter();

                using (MemoryStream ms = new MemoryStream())
                {
                    // Throws ExternalException on Windows 7,not Windows XP
                    bf.Serialize(ms,i);
                }
            }
        }
    }

对于特定的图像,我尝试了各种加载图像的方法,即使以管理员身份运行程序,也无法在Windows 7下运行.

我已将完全相同的可执行文件和图像复制到我的Windows XP VMWare实例中,我没有遇到任何问题.

任何人都知道为什么某些图像在Windows 7下不起作用,但在XP下工作?

这是其中一张图片
http://www.2shared.com/file/7wAXL88i/SO_testimage.html

delme.jpg md5:3d7e832db108de35400edc28142a8281

解决方法

正如OP指出的那样,所提供的代码抛出了一个异常,它似乎只发生在他提供的图像上,但与我机器上的其他图像一起工作正常.

选项1

static void Main(string[] args)
{
    string file = @"C:\Users\Public\Pictures\delme.jpg";

    byte[] data = File.ReadAllBytes(file);
    using (MemoryStream originalms = new MemoryStream(data))
    {
        using (Image i = Image.FromStream(originalms))
        {
            BinaryFormatter bf = new BinaryFormatter();

            using (MemoryStream ms = new MemoryStream())
            {
                // Throws ExternalException on Windows 7,not Windows XP                        
                //bf.Serialize(ms,i);

                i.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp); // Works
                i.Save(ms,System.Drawing.Imaging.ImageFormat.Png); // Works
                i.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg); // Fails
            }    
         }
     }
}

可能是有问题的图像是使用一个工具创建的,该工具添加了一些干扰JPEG序列化的附加信息.

附:可以使用BMP或PNG格式将图像保存到存储器流中.如果更改格式是一个选项,那么您可以尝试使用ImageFormat中定义的这些或任何其他格式.

选项2
如果您的目标只是将图像文件内容放入内存流中,那么执行以下操作会有所帮助

static void Main(string[] args)
{
    string file = @"C:\Users\Public\Pictures\delme.jpg";
    using (FileStream fileStream = File.OpenRead(file))
    {
        MemoryStream memStream = new MemoryStream();
        memStream.SetLength(fileStream.Length);
        fileStream.Read(memStream.GetBuffer(),(int)fileStream.Length);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐