为什么WebClient.DownloadData有时会降低图像的分辨率?

我正在尝试从网站动态下载我当前正在开发的应用程序的图标,并编写了一些代码来从给定网站中提取可能的候选者。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;

    }

正如我之前所说,在其他领域也会发生这种缩小,但在某些领域则不会。所以我想知道:

  1. 我是否错过了任何明显的事情,因为这看起来很奇怪?

  2. 为什么会发生这种情况(以及为什么其他图像文件(例如protonmail 的 48x48 px favicon)下载得很好而没有任何损失?

  3. 有没有办法更改我的代码以防止此类行为?


jeck猫
浏览 70回答 1
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();成功了。通过创建一个非常大尺寸的新图标,需要最好的质量才能将其转换为位图。
打开App,查看更多内容
随时随地看视频慕课网APP