加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – BinaryFormatter.Serialize(Image) – ExternalException

发布时间:2020-12-16 01:54:12 所属栏目:百科 来源:网络整理
导读:当我尝试使用BinaryFormatter序列化一些图像时,我会得到一个ExternalException – GDI中发生了一般性错误.“经过一段时间的努力,我决定创建一个简单的测试项目来缩小问题范围: static void Main(string[] args) { string file = @"C:tempdelme.jpg"; //Im
当我尝试使用BinaryFormatter序列化一些图像时,我会得到一个ExternalException – GDI中发生了一般性错误.“经过一段时间的努力,我决定创建一个简单的测试项目来缩小问题范围:

static void Main(string[] args)
    {
        string file = @"C:tempdelme.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:UsersPublicPicturesdelme.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:UsersPublicPicturesdelme.jpg";
    using (FileStream fileStream = File.OpenRead(file))
    {
        MemoryStream memStream = new MemoryStream();
        memStream.SetLength(fileStream.Length);
        fileStream.Read(memStream.GetBuffer(),(int)fileStream.Length);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读