为了账号安全,请及时绑定邮箱和手机立即绑定

为什么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 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信