如何使用 C# 从图标文件中检索最大的可用图像

How to retrieve the largest available image from an icon file, using C#

我需要从包含多种尺寸图像的图标文件 (.ico) 中检索最大的 位图图像。

在我的图标编辑器中,我可以看到图标文件中有几个图像,分别是 16x16px、24x24、32x32、48x48 和 256x256。

但是以下代码行错过了我想要的 256x256 图像:

var iconObj = new System.Drawing.Icon(TempFilename); //iconObj is 32x32
//get the 'default' size image:
var image1 = iconObj.ToBitmap(); //retrieved image is 32x32
//get the largest image up to 1024x1024:
var image2 = new System.Drawing.Icon(iconObj, new System.Drawing.Size(1024, 1024)).ToBitmap(); //retrieved image is 48x48

如何从图标文件中获取可用的最大图像(或特定尺寸)?

看起来,微软在他们的实现中有错误,不接受 考虑图标格式“以像素为单位指定图像宽度。可以是 0 到 255 之间的任何数字。值 0 表示图像宽度为 256 像素”。因此,从 Icon(string, size) 返回的图标的最大尺寸 可以是 128x128。 我发现了这个解决方法:当我指定 -1,-1 作为高度和宽度时,结果将是 256x256 图标(我不确定 ico 文件中图像的任何顺序,没有提供按大小排序的规范,我只是使用它在我的项目中)

using System;
using System.Drawing;

static class Program
{

    static void Main()
    {
        Icon image2 = new System.Drawing.Icon("Softskin-Series-Folder-Folder-BD-Files.ico",-1,-1);
        Console.WriteLine( "height={0} width={1}",image2.Height,image2.Width    ); 

    }
}