Save/Load a bitmap from MemoryStream, ImageConverter 'generic GDI+ error' if the stream is closed.

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Im doing a bit of processing of an image, I just need to rotate it, increase the size, and convert to 1 bit-per-pixel.
Im just having ttrouble with the below error.
Code is, at its most basic, as follows:<br/>

<pre class="prettyprint Bitmap b = new Bitmap("C:\somePic.png");

//Increase the length/width
b = new Bitmap(b, (int)(b.Width * 1.6), (int)(b.Height * 1.7));

//rotate it, flip it
b.RotateFlip(RotateFlipType.Rotate90FlipX);

//Now, for reasons I cant explain, the RoateFlip method converts the format of the bitmap.
//The size of it becomes lower so I assume its compressing it somehow?
//As such, I am having to Save it and Reload it, to get it back into a real bitmap format.
Stream imgStream = new MemoryStream();
b.Save(imgStream, ImageFormat.Bmp);
b = new Bitmap(imgStream);
//its these lines that cause the error
imgStream.Close();
imgStream.Dispose();

//convert it to a byte array to fire at a printer.
ImageConverter converter = new ImageConverter();
byte[] test = (byte[])converter.ConvertTo(b, typeof(byte[]));
[/code]
<br/>
Now the above fails the the converter.ConvertTo(...) line:<br/>
" A generic error occurred in GDI+"
<br/>
If I remove the Close()/Dispose() of the imgStream, then it works.<br/>
But then of course I have a stream left open...
Im just trying to make sense of why this is the case.

or if I could get RotateFlip to keep the image in-tact, thats even better!
(or even a more efficient way of getting my original format back).

View the full article
 
Back
Top