GDI+中发生一般性错误 Winform Image.Save(mstream, ImageFormat.Png)引发
在处理图片时,读取本地图像文件,进行另存时发生GDI+中发生一般性错误 。
具体情况如下:
用OpenFileDialog打开图像文件,文件名为filename StreamReader sr = new StreamReader(filename); Stream sm = sr.BaseStream; imgZheng = Image.FromStream(sm); sm.Close(); sr.Close(); //将读取到的Image重新写入流,转化为byte[]以便进行进一步的处理 MemoryStream mmstream = new MemoryStream(); imgZheng.Save(mmstream, ImageFormat.Png);//执行到此处时会出现“GDI+中发生一般性错误”这个错误。 byte[] imgByte = null; imgByte = mstream.ToArray();
原因:在Image.Save时也会发生这种错误,sm.Close(); sr.Close();引起。注销掉就可以正常运行,但是文件被锁定。不注销掉关闭流,再Save()将引起该错误。
解决方法如下:
byte[] ImgByte = null; MemoryStream mStream = new MemoryStream(); Bitmap bmp = new Bitmap(filename); bmp.Save(mStream, ImageFormat.Png); ImgByte = mStream.ToArray(); bmp.Dispose(); mStream.Close(); MemoryStream mstream = new MemoryStream(ImgByte); imgZheng = Image.FromStream(mstream); mstream.Close();
//此时再执行Save方法,将不会报错
MemoryStream mstream = new MemoryStream();
imgZheng.Save(mstream, ImageFormat.Png);
方法二:
StreamReader sr = new StreamReader(filename); Stream sm = sr.BaseStream; Image img = Image.FromStream(sm); img = Image.FromStream(sm);
//将图像序列化给指定的流,再将流序列化为二进制数组。 BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream mstream = new MemoryStream(); binaryFormatter.Serialize(mstream, img); byte[] ImgByte = mstream.ToArray(); mstream.Close(); sm.Close(); sr.Close(); //将二进制数组放到流中,再反序列为图像 MemoryStream memostream = new MemoryStream(ImgByte); imgZheng = (Image)binaryFormatter.Deserialize(memostream); memostream.Close();
//此时再执行Save方法,将不会报错
MemoryStream mstream = new MemoryStream();
imgZheng.Save(mstream, ImageFormat.Png);
方法三:(与方法二相比,流的赋值方式不一样,流转换为图像的方式也不一样)
StreamReader sr = new StreamReader(filename); Stream sm = sr.BaseStream; Image img = Image.FromStream(sm); img = Image.FromStream(sm); MemoryStream mstream = new MemoryStream(); img.Save(mstream, ImageFormat.Png); byte[] ImgByte = mstream.ToArray(); mstream.Close(); sm.Close(); sr.Close(); MemoryStream mmstream = new MemoryStream(ImgByte); imgZheng = Image.FromStream(mmstream); mmstream.Close();
//此时再执行Save方法,将不会报错
MemoryStream mstream = new MemoryStream();
imgZheng.Save(mstream, ImageFormat.Png);