我无法从网址中检索图像。以前我在设置HttpClient标头之前根本无法连接到该网站。我能够从其他来源检索图像,但不是这个特定的图像。
检索图像的代码:
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;
如果我尝试使用不同的网址检索不同的图像,例如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。
您可以通过在请求网址中使用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图像,并首先在System.Drawing.Bitmap
库的帮助下将其转换为libwebp wrapper for .NET。然后第二次转换从System.Drawing.Bitmap
转换为BitmapImage
:
包装库可以通过NuGet获得,但您还必须下载所需平台的包装libwebp
库,即x86或x64,如包装库主页上所述。
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");