WPF 无法从 url 检索 WebP 图像?

WPF Can't retrieve WebP image from url?

我无法从 url 检索图像。以前我根本无法连接到站点,直到我设置 HttpClient headers。我可以从其他来源检索图像,但不能从这个特定来源检索图像。

检索图像代码:

var img = new BitmapImage();
        img.BeginInit();
        img.UriSource = new Uri("https://i1.adis.ws/i/jpl/jd_083285_a?qlt=80&w=600&h=425&v=1&fmt=webp", UriKind.RelativeOrAbsolute);
        img.EndInit();
        Console.Out.WriteLine();
        ImageShoe.Source = img;

如果我尝试使用不同的 url 检索不同的图像,例如 https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png 它工作正常。

更新:

似乎使用字节数组是可行的方法,但我仍然不确定这里有什么问题。

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        var url = "https://i1.adis.ws/i/jpl/jd_083285_a?qlt=80&w=600&h=425&v=1&fmt=webp";//baseUrl + productUrl;
        var result = await client.GetByteArrayAsync(new Uri(
        MemoryStream buf = new MemoryStream(result);
        var image = new BitmapImage();
        image.StreamSource = buf;
        this.ImageShoe.Source = image;

WPF 本身不支持 WebP image format

您可以通过在请求 URL:

中使用 fmt=png 而不是 fmt=webp 来简单地请求支持的格式,例如 PNG
ImageShoe.Source = new BitmapImage(
    new Uri("https://i1.adis.ws/i/jpl/jd_083285_a?qlt=80&w=600&h=425&v=1&fmt=png"));

如果您确实需要 WebP 支持,以下方法会下载 WebP 图像并首先在 libwebp wrapper for .NET 库的帮助下将其转换为 System.Drawing.Bitmap。第二次转换然后从 System.Drawing.Bitmap 转换为 BitmapImage:

包装器库可通过 NuGet 获得,但您还必须下载适用于所需平台(即 x86 或 x64)的包装器 libwebp 库,如包装器库主页上所述。

private async Task<BitmapImage> LoadWebP(string url)
{
    var httpClient = new HttpClient();
    var buffer = await httpClient.GetByteArrayAsync(url);
    var decoder = new Imazen.WebP.SimpleDecoder();
    var bitmap = decoder.DecodeFromBytes(buffer, buffer.Length);
    var bitmapImage = new BitmapImage();

    using (var stream = new MemoryStream())
    {
        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Position = 0;

        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
    }

    return bitmapImage;
}

我用

测试过
ImageShoe.Source = await LoadWebP(
    "https://i1.adis.ws/i/jpl/jd_083285_a?qlt=80&w=600&h=425&v=1&fmt=webp");