现象
- 代码
// buff为一个存储了jpeg文件数据的byte[]
MemoryStream ms = new MemoryStream(buff);
Image img = Image.FromStream(ms);
ms.Close();
string path = "D:\\test.jpg";
// 当执行Save方法时出现异常
img.Save(path);
- 异常信息
GDI+ 中发生一般性错误。“System.Runtime.InteropServices.ExternalException”(位于 System.Drawing.dll 中)
原因
You must keep the stream open for the lifetime of the Image. 详情见msdn
解决
注释掉 ms.Close()
// buff为一个存储了jpeg文件数据的byte[]
MemoryStream ms = new MemoryStream(buff);
Image img = Image.FromStream(ms);
// ms.Close();
string path = "D:\\test.jpg";
// 可以正常保存图像了
img.Save(path);