tabina
tabina

Reputation: 1155

BitmapImage from file PixelFormat is always bgr32

I am loading an image from file with this code:

BitmapImage BitmapImg = null;
BitmapImg = new BitmapImage();
BitmapImg.BeginInit();
BitmapImg.UriSource = new Uri(imagePath);
BitmapImg.CacheOption = BitmapCacheOption.OnLoad;
BitmapImg.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
BitmapImg.EndInit();

It works as expected except for the fact that no matter what kind of image I'm loading (24bit RGB, 8bit grey, 12bit grey,...), after .EndInit() the BitmapImage always has as Format bgr32. I know there have been discussions on the net, but I have not found any solution for this problem. Does anyone of you know if it has been solved yet?

Thanks,

tabina

Upvotes: 4

Views: 3645

Answers (2)

Keith Stein
Keith Stein

Reputation: 6724

For some reason I don't understand, using BitmapCreateOptions.PreservePixelFormat with new BitmapImage() didn't work for me. But this did lead me onto the right track. If anyone else tries the other answer and it doesn't work, this alternate method is what worked for me:

var decoder = new PngBitmapDecoder(new Uri(imagePath), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapFrame frame = decoder.Frames[0];

For whatever reason PngBitmapDecoder worked where BitmapImage didn't.
Note: BitmapFrame inherits BitmapSource just like BitmapImage, for my purpose that was all I needed.

Upvotes: 0

Clemens
Clemens

Reputation: 128060

From the Remarks section in BitmapCreateOptions:

If PreservePixelFormat is not selected, the PixelFormat of the image is chosen by the system depending on what the system determines will yield the best performance. Enabling this option preserves the file format but may result in lesser performance.

Therefore you also need to set the PreservePixelFormat flag:

var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(imagePath);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache
                     | BitmapCreateOptions.PreservePixelFormat;
bitmap.EndInit();

Upvotes: 3

Related Questions