WPF通过代码加载jpg图像出错 - BitmapMetadata在BitmapImage上不可用

3

这让我非常沮丧。

我在通过代码加载JPG图像时遇到了问题。如果我在XAML中加载相同的图像,则可以正确加载。

例如:

<Image Source="Assets/Images/Backgrounds/ChangeSelectionImg.jpg" />

但是这段代码无法加载相同的图片,但对于PNG图片却可以正常工作:
var uriSource = new Uri(@"C:\Work\TestApp\Assets\Images\Backgrounds\ChangeSelectionImg.jpg", UriKind.Absolute);

var bmi = new BitmapImage();
bmi.BeginInit();
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bmi.UriSource = uriSource;
bmi.EndInit();
var image = new Image
{
    Width = 187,
    Height = 700,
    StretchDirection = StretchDirection.DownOnly,
    Stretch = Stretch.Fill,
    Source = bmi
};

SpImage.Children.Add(image);

我没有试过使用相对URI,因为我想要加载的实际图像是应用程序外部的文件夹。图像路径将在数据库中指定。

甚至尝试了BitmapCreateOptions.IgnoreColorProfile选项,如这里建议的那样,但也没有起作用。

以下代码适用于PNG图像,但不适用于jpg:

var imagePath = "some absolute path to an image";
var uriSource = new Uri(imagePath, UriKind.Absolute);

var image = new Image
{
    Width = 187,
    Height = 700,
    StretchDirection = StretchDirection.DownOnly,
    Stretch = Stretch.Fill,
    Source = new BitmapImage(uriSource)
};

我现在没有什么创意,非常需要帮助。

2个回答

0

由于我无法弄清楚为什么会发生这种情况,也没有人帮忙 :( 以防其他人陷入同样的困境,这是我决定做的事情:

var bannerImg = new ImageBrush(new BitmapImage(uriSource))
{
    Stretch = Stretch.Uniform
};

SpImage.Background = bannerImg;

我将StackPanel的背景图片设置为该图片。

我仍然乐意听取建议。


0

BitMapImage不支持BitMapMetaData,会抛出System.NotSupported异常,使用JpegBitmapDecoder可以解决此问题。


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