I am trying to save an image into a MemoryStream but it is failing under certain conditions.
Here is the code:
The following code succeeds:
Image img = Bitmap.FromStream(fileStream);
MemoryStream ms = new MemoryStream();
img.Save(ms, img.RawFormat); // This succeeds.
The following code fails:
Image img = Bitmap.FromStream(fileStream);
Image thumb = img.GetThumbnailImage(thumbWidth, thumbHeight, null, System.IntPtr.Zero);
MemoryStream ms = new MemoryStream();
thumb.Save(ms, thumb.RawFormat); // This fails.
Notice that the second snippet is using an image created using Image.GetThumbnailImage.
What is the difference? Does anyone have any idea why is it failing?
I believe the problem has to do with this part of the
GetThumbnailImagedocumentation:This probably accounts for the intermittent behaviour (AKA “certain conditions”). The explanation is in the following Microsoft Connect ticket:
In all likelihood, if there is no embedded thumbnail, the new thumbnail generated by the
GetThumbnailImageAPI is in fact going to have aRawFormatofMemoryBmpwhich has no associated encoder – thus the specific error message you’re seeing.Just don’t use
thumb.RawFormat; since you know it’s a bitmap anyway, useImageFormat.Bmpinstead.P.S. Please note that although I deleted my earlier answer because it turned out to not to be relevant to this particular issue, it is still important to use the
GetThumbnailImageAPI properly as the documentation specifies; you must pass a valid delegate for thecallbackparameter instead ofnull, otherwise it can fail, and you still need to be wrapping disposables inusingclauses.