c# - Image.Save(..) 抛出 GDI+ 异常,因为内存流已关闭

标签 c# image exception gdi+

我有一些二进制数据,我想将其保存为图像。当我尝试保存图像时,如果用于创建图像的内存流在保存之前关闭,则会引发异常。我这样做的原因是因为我正在动态创建图像,因此我需要使用内存流。

这是代码:

[TestMethod]
public void TestMethod1()
{
    // Grab the binary data.
    byte[] data = File.ReadAllBytes("Chick.jpg");

    // Read in the data but do not close, before using the stream.
    Stream originalBinaryDataStream = new MemoryStream(data);
    Bitmap image = new Bitmap(originalBinaryDataStream);
    image.Save(@"c:\test.jpg");
    originalBinaryDataStream.Dispose();

    // Now lets use a nice dispose, etc...
    Bitmap2 image2;
    using (Stream originalBinaryDataStream2 = new MemoryStream(data))
    {
        image2 = new Bitmap(originalBinaryDataStream2);
    }

    image2.Save(@"C:\temp\pewpew.jpg"); // This throws the GDI+ exception.
}

有没有人对我如何在关闭流的情况下保存图像有任何建议?我不能指望开发人员记得在保存图像后关闭流。事实上,开发人员不会知道图像是使用内存流生成的(因为它发生在其他代码中,其他地方)。

我真的很困惑:(

最佳答案

因为它是一个 MemoryStream,所以您确实不需要关闭流 - 如果您不这样做,也不会发生什么不好的事情,尽管显然处置任何一次性的东西都是一种很好的做法。 (有关更多信息,请参阅 this question。)

但是,您应该处理位图 - 这将为您关闭流。基本上,一旦您为 Bitmap 构造函数提供了一个流,它就“拥有”该流,您不应该关闭它。作为the docs for that constructor说:

You must keep the stream open for the lifetime of the Bitmap.

我找不到任何 promise 在您处理位图时关闭流的文档,但您应该能够相当容易地验证这一点。

关于c# - Image.Save(..) 抛出 GDI+ 异常,因为内存流已关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/336387/

相关文章:

c# - 有没有更好的方法来缩小从 aspx 页面生成的 html

c# - 底层表单消失但仅当对话框显示时

html - 将侧边栏与图像分开

java - 删除实体会导致 hibernate 中的 ObjectDeletedException

java - 如果方法不适合当前对象,则抛出哪个异常

c# - 从模拟的 ApplicationUserManager.Users 返回用户

c# - 如何设置asp.net Identity cookies过期时间

java - 绘制图像的形状

python - Matplotlib 不全屏保存图像

c++ - 关于与return语句一起发生的异常的问题