我正在嘗試從網站動態下載我當前正在開發的應用程序的圖標,并編寫了一些代碼來從給定網站中提取可能的候選者。WebClient.DownloadData這一切都工作正常,但由于某種原因,在下載某些圖像文件而其他圖像文件按預期下載后,質量會出現很大損失。例如,使用以下代碼下載Microsoft 的 128 x 128 像素圖標會生成 16 x 16 像素位圖: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;? ? }正如我之前所說,在其他領域也會發生這種縮小,但在某些領域則不會。所以我想知道:我是否錯過了任何明顯的事情,因為這看起來很奇怪?為什么會發生這種情況(以及為什么其他圖像文件(例如protonmail 的 48x48 px favicon)下載得很好而沒有任何損失?有沒有辦法更改我的代碼以防止此類行為?
1 回答

月關寶盒
TA貢獻1772條經驗 獲得超5個贊
正如所指出的,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();
成功了。
通過創建一個非常大尺寸的新圖標,需要最好的質量才能將其轉換為位圖。
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消