我有一些二进制数据,我想保存为图像。当我尝试保存图像时,如果用于创建图像的内存流在保存之前已关闭,则会引发异常。我这样做的原因是因为我正在动态创建图像,因此..我需要使用内存流。
这是代码:
[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.
}
有人对我如何在流关闭的情况下保存图像有任何建议吗?我不能依赖开发人员记住在图像保存后关闭流。事实上,开发人员不知道图像是使用内存流生成的(因为它发生在其他一些代码中,其他地方)。
我真的很困惑:(