这个错误经常发生,代码如下:
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(Bitmap bitmap = new Bitmap(image))
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;
}
}
}
关于图片文件被占用的问题 可以使用filestream先读取在转成 image在关闭文件流既可。