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

有帮助吗?

解决方案

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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top