gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:12:55 43 4
gpt4 key购买 nike

当我尝试使用 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 序列化的额外信息的工具创建的。

附言图像可以使用BMPPNG 格式保存到内存流中。如果可以选择更改格式,那么您可以尝试使用这些格式或 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(), 0, (int)fileStream.Length);
}
}

关于c# - BinaryFormatter.Serialize( Image ) - ExternalException - GDI+ 中发生一般错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15916661/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com