How to make an icon

August 26, 2007 at 6:43 am | Posted in .Net, C# | Leave a comment

Apparently, .Net does not provide a good set of classes to create icons programmatically.  In helping someone on a forum, I ran across a free tool for image processing that does a great job.

The technique uses a free .dll called FreeImage. I gave it a try and with the help of a wrapper found in CodeProject was able to convert a .bmp file to a .ico file.

Here are the steps:

1. Download the FreeImage .dll from here.

2. Copy the .dll into the bin/Debug and/or bin/Release folder in your project

3. Add an Enum and FreeImage Class to your project (shown in the example below).

4. Use three calls to the functions in FreeImage: load the bitmap file, save in icon format, release the resource.

The following example loads a .bmp into FreeImage and saves it back as a .ico file. It includes the required Enum and FreeImage Class. (Requires using System.Runtime.InteropServices; )

class Program
{
    static void Main(string[] args)
    {
        int handle = FreeImage.FreeImage_Load(
            FIF.FIF_BMP,
            @"C:\Documents and Settings\User\Desktop\myBmp.bmp", 
            0);
                      
        FreeImage.FreeImage_Save(
            FIF.FIF_ICO,   
            handle, 
            @"C:\Documents and Settings\User\Desktop\new.ico", 
            0);
 
        FreeImage.FreeImage_Unload(handle);         

    }
}

public enum FIF
{
    FIF_UNKNOWN = -1,
    FIF_BMP = 0,
    FIF_ICO = 1,
    FIF_JPEG = 2,
    FIF_JNG = 3,
    FIF_KOALA = 4,
    FIF_LBM = 5,
    FIF_MNG = 6,
    FIF_PBM = 7,
    FIF_PBMRAW = 8,
    FIF_PCD = 9,
    FIF_PCX = 10,
    FIF_PGM = 11,
    FIF_PGMRAW = 12,
    FIF_PNG = 13,
    FIF_PPM = 14,
    FIF_PPMRAW = 15,
    FIF_RAS = 16,
    FIF_TARGA = 17,
    FIF_TIFF = 18,
    FIF_WBMP = 19,
    FIF_PSD = 20,
    FIF_CUT = 21,
    FIF_IFF = FIF_LBM,
    FIF_XBM = 22,
    FIF_XPM = 23
}
public class FreeImage
{
     [DllImport("FreeImage.dll")]
     public static extern int FreeImage_Load(FIF format, 
                    string filename, int flags);
     
     [DllImport("FreeImage.dll")]
     public static extern void FreeImage_Unload(int handle);
     
     [DllImport("FreeImage.dll")]
     public static extern bool FreeImage_Save(FIF format, 
        int handle, string filename, int flags);
}
Advertisements

Leave a Comment »

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.
Entries and comments feeds.

%d bloggers like this: