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