GDI+中发生一般性错误的解决办法

//错误代码     Bitmap 对象或一个 图像 对象从一个文件, 构造时该文件仍保留锁定对于对象的生存期。 因此, 无法更改图像并将其保存回它产生相同的文件。
private
static byte[] GetBytes (Image image) { try { if (image == null) return null; using (MemoryStream stream = new MemoryStream()) { image .Save(stream, ImageFormat.Jpeg); return stream.GetBuffer(); } } finally { if(image != null) { image.Dispose(); image = null; } } }
//修改后的  拷贝这个对象,生成一个副本,再来操作这个副本,就能够解决这个问题 ,见using语法 Dispose
private
static byte[] GetBytes (Image image) { try { if (image == null) return null; using(Bitmap bitmap = new Bitmap(image)) { using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Jpeg); return stream.GetBuffer(); } } } finally { if(image != null) { image.Dispose(); image = null; } } }


 
原文地址:https://www.cnblogs.com/yc1224/p/13985068.html