Max*_*Max 0 c# url wpf web-scraping webp
我无法从 url 中检索图像。以前,在设置 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;
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用不同的 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;
Run Code Online (Sandbox Code Playgroud)
WPF 本身不支持WebP 图像格式。
您可以简单地请求支持的格式,如 PNG,通过在请求 URL 中使用fmt=png而不是fmt=webp:
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"));
Run Code Online (Sandbox Code Playgroud)
如果您确实需要 WebP 支持,以下方法会下载一个 WebP 图像,并首先在 .NET库System.Drawing.Bitmap的libwebp 包装器的帮助下将其转换为。第二次转换然后转换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;
}
Run Code Online (Sandbox Code Playgroud)
我已经测试过了
ImageShoe.Source = await LoadWebP(
"https://i1.adis.ws/i/jpl/jd_083285_a?qlt=80&w=600&h=425&v=1&fmt=webp");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1751 次 |
| 最近记录: |