WPF Can't retrieve WebP image from url?

前端 未结 1 1072
一整个雨季
一整个雨季 2021-01-29 05:16

I\'m unable to retrieve an image from a url. Previously I was unable to connect to the site at all until I set HttpClient headers. I\'m able to retrieve images from other source

相关标签:
1条回答
  • 2021-01-29 05:47

    WPF does not natively support the WebP image format.

    You could simply request a supported format like PNG, by using fmt=png instead of fmt=webp in the request URL:

    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"));
    

    If you really need WebP support, the following methods downloads a WebP image and first converts it to a System.Drawing.Bitmap with help of the libwebp wrapper for .NET library. A second conversion then converts from System.Drawing.Bitmap to BitmapImage:

    The wrapper library is available via NuGet, but you also have to download the wrapped libwebp library for the desired platform, i.e. x86 or x64, as explained on the wrapper library's home page.

    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;
    }
    

    I've tested it with

    ImageShoe.Source = await LoadWebP(
        "https://i1.adis.ws/i/jpl/jd_083285_a?qlt=80&w=600&h=425&v=1&fmt=webp");
    
    0 讨论(0)
提交回复
热议问题