I recently found some images on the internet in a format that I couldn’t directly support in my applications. The images were in JPEG XR, with a .jxr extension. These images would fail with a “The parameter is incorrect” error when loading the byte array into a System.Drawing.Bitmap (using Image.FromStream).
A little bit of research showed that the standard Drawing classes wouldn’t support this format. I would need to use classes from the WPF library. I added references to PresentationCore and WindowsBase, then wrote this function to convert the bytes of a JXR image to a standard bitmap:
Private Function JXRToBitmap(bytes() As Byte) As Bitmap Dim s As IO.MemoryStream Dim dec As Windows.Media.Imaging.WmpBitmapDecoder Dim enc As Windows.Media.Imaging.BmpBitmapEncoder Dim bmp As Bitmap s = New IO.MemoryStream dec = New Windows.Media.Imaging.WmpBitmapDecoder(New IO.MemoryStream(bytes), Windows.Media.Imaging.BitmapCreateOptions.None, Windows.Media.Imaging.BitmapCacheOption.Default) enc = New Windows.Media.Imaging.BmpBitmapEncoder enc.Frames.Add(Windows.Media.Imaging.BitmapFrame.Create(dec.Frames(0))) enc.Save(s) bmp = New Bitmap(s) s.Dispose() Return bmp End Function
Since I didn’t know in advance what the file format was, the best I could do was attempt to load the bitmap and if it threw an exception, I would try to load it again using this function in the Catch block. If that failed, then it would be a true exception.