亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么WebClient.DownloadData有時會降低圖像的分辨率?

為什么WebClient.DownloadData有時會降低圖像的分辨率?

C#
jeck貓 2023-06-25 14:18:07
我正在嘗試從網站動態下載我當前正在開發的應用程序的圖標,并編寫了一些代碼來從給定網站中提取可能的候選者。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();

成功了。


通過創建一個非常大尺寸的新圖標,需要最好的質量才能將其轉換為位圖。


查看完整回答
反對 回復 2023-06-25
  • 1 回答
  • 0 關注
  • 121 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號