Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you access icons from a Multi-Icon (.ico) file using index in C#

Tags:

c#

indexing

icons

I want to use the 4th image from the ico file : C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\VS2008ImageLibrary\1033\VS2008ImageLibrary\VS2008ImageLibrary\Objects\ico_format\WinVista\Hard_Drive.ico

If I see this icon using Windows Photo Viewer, shows me 13 different icons.

I have dumped this ico in a resource file, how can I retreive the required icon using index.

like image 554
Nitin Chaudhari Avatar asked Jan 05 '12 11:01

Nitin Chaudhari


2 Answers

In WPF, you can do something like this:

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 );
}
like image 194
Stephan Bauer Avatar answered Nov 18 '22 11:11

Stephan Bauer


You'll need to manually parse through the .ico file grabbing information from the header (see here for a layout of the .ico file type).

There's an open source project on vbAccelerator (don't worry it's actually c# code, not VB) that uses the Win32 API to extract icons from resources (exe, dll and even ico, which is what you are looking to do). You could either use that code or go through it for an good idea of how it is done. The source code can be browsed here.

like image 5
Jason Down Avatar answered Nov 18 '22 12:11

Jason Down