从文件创建的BitmapImage像素格式始终为bgr32。

4

我正在使用以下代码从文件中加载一张图片:

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

除了一个问题,它的工作效果符合预期。无论我加载什么类型的图像(24位RGB、8位灰度、12位灰度等),在完成初始化(.EndInit())后,BitmapImage总是以bgr32格式显示。我知道有些讨论在网络上进行,但我还没有找到解决此问题的方法。您们谁知道是否已经解决了这个问题?
谢谢, tabina
2个回答

3

BitmapCreateOptions中的注释部分:

如果未选择保留像素格式,则系统将根据能够产生最佳性能的系统来决定图像的像素格式。启用此选项会保留文件格式,但可能会导致性能降低。

因此,您还需要设置PreservePixelFormat标志:

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

0
由于某些我不理解的原因,使用BitmapCreateOptions.PreservePixelFormatnew BitmapImage()在我的情况下没有起作用。但这确实让我走上了正确的轨道。如果其他人尝试了另一个答案并且它不起作用,那么这种替代方法就是对我有效的方法:
var decoder = new PngBitmapDecoder(new Uri(imagePath), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapFrame frame = decoder.Frames[0];

无论出于何种原因,PngBitmapDecoder 能够正常工作,而 BitmapImage 却不能。
注意:对于我的目的来说,BitmapFrameBitmapImage 一样继承自 BitmapSource,这就是我所需要的全部内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接