Image.Save(..)抛出GDI +的异常,因为内存流关闭 [英] Image.Save(..) throws a GDI+ exception because the memory stream is closed

查看:124
本文介绍了Image.Save(..)抛出GDI +的异常,因为内存流关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到了我想要保存为图像一些二进制数据。当我尝试保存图像时,它抛出,如果用来创建映像的内存流,是之前保存关闭异常。我之所以这样做是因为我动态创建的图像,因此..我需要使用内存流。

i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.

这是code:

[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.
}

有没有人要我怎么可以节省与流的图像关闭有什么建议?我不能依靠开发商要记住的图像保存后关闭流。事实上,开发商根本不知道该图像是使用一个内存流(因为它发生在其他一些code,其它地方)产生的。

Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).

我真的很困惑:(

推荐答案

由于这是一个MemoryStream,你真的不知道的需求的关闭流 - 没有什么不好的,如果你不这样做会发生,但显然,这是很好的做法,处理任何的可支配反正。 (请参见更多关于这个这个问题。)

As it's a MemoryStream, you really don't need to close the stream - nothing bad will happen if you don't, although obviously it's good practice to dispose anything that's disposable anyway. (See this question for more on this.)

不过,你的的是处理位图 - 这将关闭流为您服务。基本上,一旦你给位图的构造一个流,它拥有流,你不应该将其关闭。至于该构造的文档说:

However, you should be disposing the Bitmap - and that will close the stream for you. Basically once you give the Bitmap constructor a stream, it "owns" the stream and you shouldn't close it. As the docs for that constructor say:

您必须保持开放的流为
  寿命的位图

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

我找不到任何文档看好,当你处理位图,关闭流,但你应该能够验证相当容易。

I can't find any docs promising to close the stream when you dispose the bitmap, but you should be able to verify that fairly easily.

这篇关于Image.Save(..)抛出GDI +的异常,因为内存流关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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