我正在尝试从网站上动态下载网站图标,以用于我当前正在处理的应用程序,并找到了方便的web API来执行此操作。一切正常,但由于某些原因,对于某些图像文件使用WebClient.DownloadData
下载后,而其他文件却按预期下载,质量会大大下降。
例如,使用以下代码下载Microsoft's 128 x 128 px favicon会生成16 x 16 px的位图:
public static string Temp()
{
string iconLink = "https://c.s-microsoft.com/favicon.ico?v2"; // <-- 128 x 128 PX FAVICON
ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
SecurityProtocolType[] protocolTypes = new SecurityProtocolType[] { SecurityProtocolType.Ssl3, SecurityProtocolType.Tls, SecurityProtocolType.Tls11, SecurityProtocolType.Tls12 };
string base64Image = string.Empty;
bool successful = false;
for (int i = 0; i < protocolTypes.Length; i++)
{
ServicePointManager.SecurityProtocol = protocolTypes[i];
try
{
using (WebClient client = new WebClient())
using (MemoryStream stream = new MemoryStream(client.DownloadData(iconLink)))
{
Bitmap bmpIcon = new Bitmap(Image.FromStream(stream, true, true));
if (bmpIcon.Width < 48 || bmpIcon.Height < 48) // <-- THIS CHECK FAILS, DEBUGGER SAYS 16 x 16 PX!
{
break;
}
bmpIcon = (Bitmap)bmpIcon.GetThumbnailImage(350, 350, null, new IntPtr());
using (MemoryStream ms = new MemoryStream())
{
bmpIcon.Save(ms, ImageFormat.Png);
base64Image = Convert.ToBase64String(ms.ToArray());
}
}
successful = true;
break;
}
catch { }
}
if (!successful)
{
throw new Exception("No Icon found");
}
return base64Image;
}
正如我之前所述,在其他域中也会发生这种缩小,然后在某些域中则没有。 所以我想知道:
答案 0 :(得分:1)
如前所述,Image.FromStream()
不会自动选择处理.ico文件时可用的最佳质量。
因此需要更改
Bitmap bmpIcon = new Bitmap(Image.FromStream(stream, true, true));
到
System.Drawing.Icon originalIcon = new System.Drawing.Icon(stream);
System.Drawing.Icon icon = new System.Drawing.Icon(originalIcon, new Size(1024, 1024));
Bitmap bmpIcon = icon.ToBitmap();
成功了!
通过创建一个很大的新图标,它将获得可用于转换为位图的最佳质量。