A generic error occurred in GDI+, JPEG Image to MemoryStream

OK I seem to have found the cause just by sheer luck and its nothing wrong with that particular method, it’s further back up the call stack.

Earlier I resize the image and as part of that method I return the resized object as follows. I have inserted two calls to the above method and a direct save to a file.

// At this point the new bitmap has no MimeType
// Need to output to memory stream
using (var m = new MemoryStream())
       dst.Save(m, format);

       var img = Image.FromStream(m);

       var bytes = PhotoEditor.ConvertImageToByteArray(img);

       return img;

It appears that the memory stream that the object was created on has to be open at the time the object is saved. I am not sure why this is. Is anyone able to enlighten me and how I can get around this.

I only return from a stream because after using the resize code similar to this the destination file has an unknown mime type (img.RawFormat.Guid) and Id like the Mime type to be correct on all image objects as it makes it hard write generic handling code otherwise.


This didn’t come up in my initial search but here’s the answer from Jon Skeet

Leave a Comment