WPF: Finicky About JPEGs

293 words.

Gah! I’ve found that WPF’s BitmapImage is quite finicky about the kind of JPEG files it will load.

For example: I have a huge directory of genealogy pictures originally scanned in high-resolution TIFF format. I also have a mirror of the pictures saved in smaller-sized JPEG format, which was created with a utility I wrote utilizing the Independent JPEG Group’s library. Sadly, WPF wouldn’t load any of those JPEGs:

System.IO.FileFormatException: The image decoder cannot decode the image. The image might be corrupted. —> System.Runtime.InteropServices.COMException (0x88982F60): Exception from HRESULT: 0x88982F60

Naturally they worked just fine in the Vista Explorer and, well, basically everywhere except my new WPF test app.

At first I thought it was because my JPEGs were saved as progressive scan JPEGs, but that wasn’t it.

I turned to Google, and found exactly one hit related to my problem:  This Microsoft forum post. It turns out the problem is in the Windows Imaging Component (WIC), which I think is new in Vista.  I should say it’s actually a problem that WIC thinks is in my JPEGs. I got WIC Explorer from the Windows Imaging Component Code Samples and Tools to investigate further. WIC Explorer also threw an error, but it was still able to load and display my JPEG image despite the error.

That led me to try catching the offending FileFormatException and proceed anyway, but the BitmapImage was not complete and could not be used.

So I looked at that forum post again and discovered the original poster had solved his problem with the BitmapCreateOptions.IgnoreColorProfile flag. I added that and voila, problem solved.

BitmapImage bitmap = new BitmapImage();

bitmap.BeginInit();

bitmap.StreamSource = stream;

bitmap.CacheOption = BitmapCacheOption.OnLoad;

// IgnoreColorProfile solves FileFormatExceptions with JPEGs created by IJG.

bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;

bitmap.DecodePixelWidth = 600;

bitmap.EndInit();

Related

This page is a static archival copy of what was originally a WordPress post. It was converted from HTML to Markdown format before being built by Hugo. There may be formatting problems that I haven't addressed yet. There may be problems with missing or mangled images that I haven't fixed yet. There may have been comments on the original post, which I have archived, but I haven't quite worked out how to show them on the new site.

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.