Image.Save(..) 抛出 GDI+ 异常,因为内存流已关闭 [英] Image.Save(..) throws a GDI+ exception because the memory stream is closed
问题描述
我有一些二进制数据要保存为图像.当我尝试保存图像时,如果用于创建图像的内存流在保存之前关闭,则会引发异常.我这样做的原因是因为我正在动态创建图像,因此..我需要使用内存流.
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.
这是代码:
[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: est.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: emppewpew.jpg"); // This throws the GDI+ exception.
}
有人对我如何在关闭流的情况下保存图像有任何建议吗?我不能依赖开发人员记住在保存图像后关闭流.事实上,开发人员不知道图像是使用内存流生成的(因为它发生在其他地方的其他代码中).
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.)
但是,您应该处理位图 - 这将为您关闭流.基本上,一旦您为 Bitmap 构造函数提供了一个流,它就拥有"了该流,您不应关闭它.正如该构造函数的文档所说:
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屋!