我无法从网址检索图像。以前,在设置 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 https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png效果很好。
Update:
似乎使用字节数组是可行的方法,但我仍然不确定这里出了什么问题。
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 图像格式 https://en.wikipedia.org/wiki/WebP.
您可以简单地通过使用来请求支持的格式,例如 PNGfmt=png
代替fmt=webp
在请求 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"));
如果您确实需要 WebP 支持,可以使用以下方法下载 WebP 图像并首先将其转换为System.Drawing.Bitmap
在的帮助下.NET 的 libwebp 包装器 https://github.com/imazen/libwebp-net图书馆。然后进行第二次转换System.Drawing.Bitmap
to 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");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)