如何使用C#中的索引从多图标(.ico)文件访问图标

我想使用ico文件中的第4个图像C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\VS2008ImageLibrary\1033\VS2008ImageLibrary\VS2008ImageLibrary\Objects\ico_format\WinVista\Hard_Drive.ico

如果我使用Windows Photo Viewer看到此图标,则会显示13个不同的图标。

我已将此ico转储到资源文件中,如何使用索引检索所需的图标。

在WPF中,您可以执行以下操作:

 Stream iconStream = new FileStream ( @"C:\yourfilename.ico", FileMode.Open ); IconBitmapDecoder decoder = new IconBitmapDecoder ( iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None ); // loop through images inside the file foreach ( var item in decoder.Frames ) { //Do whatever you want to do with the single images inside the file this.panel.Children.Add ( new Image () { Source = item } ); } // or just get exactly the 4th image: var frame = decoder.Frames[3]; // save file as PNG BitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(frame); using ( Stream saveStream = new FileStream ( @"C:\target.png", FileMode.Create )) { encoder.Save( saveStream ); } 

您需要手动解析.ico文件从标题中获取信息(有关.ico文件类型的布局,请参见此处 )。

在vbAccelerator上有一个开源项目 (不要担心它实际上是c#代码,而不是VB),它使用Win32 API从资源中提取图标(exe,dll甚至ico,这是你想要做的)。 您既可以使用该代码,也可以通过它来了解它是如何完成的。 可以在此处浏览源代码。