Converting a Bitmap to an Icon using .NET

This is something that most programmers will want to do at some point: convert a bitmap to an icon. This is possible in .net, but it’s not completely obvious, so I thought I’d write a short how to.

Firstly, you’ll need a Bitmap object, you can create your own Bitmap object using one of its many constructors, or use the static method FromFile in the Image class. For this example, we’ll assume that there’s a valid bitmap file at C:\x.bmp.

To get the Icon object, you’ll need to use the static method of the Icon class FromHandle(IntPtr). Getting the handle is as simple as calling the instance method GetHicon() of the Bitmap class.

For example:

  1. /*
  2. Requires System.Drawing
  3. Note: Image.FromFile(string) is not limited to loading bmp files,
  4. it can be used to load others including jpg, gif and png.
  5. */
  6. string bmpFile = @”C:\x.bmp";
  7. string icoFile = @”C:\x.ico";
  8. Bitmap b = (Bitmap)Image.FromFile(bmpFile);
  9. Icon i = Icon.FromHandle(b.GetHicon());

To save the icon, just use the instance method Save(FileStream).

  1. /*
  2. Requires System.Drawing, System.IO
  3. */
  4. FileStream fs = File.Open(icoFile, FileMode.Create);
  5. i.Save(fs);
  6. fs.Close();

There, it’s not as obvious as an Image.ToIcon() implementation, especially for those of us not used to handling pointers, but it works. That should stop you from downloading those dodgy shareware icon converters :).

Just to finish off, here’s the code used to generate the favicon.ico¬†for this site (without any calls to Dispose() or any dereferencing):

  1. Bitmap b = new Bitmap(16, 16);
  2. Rectangle rMiddle = new Rectangle(0, 0, 16, 16);
  3. Graphics g = Graphics.FromImage(b);
  4. StringFormat format = new StringFormat();
  5. format.Alignment = StringAlignment.Center;
  6. format.LineAlignment = StringAlignment.Center;
  7. g.SmoothingMode = SmoothingMode.HighQuality;
  8. g.Clear(Color.Transparent);
  9. g.FillRectangle(Brushes.Blue, rMiddle);
  10. g.DrawString("a", new Font("Tahoma", 12f),
  11.     Brushes.Cornsilk, rMiddle, format);
  12. Icon i = Icon.FromHandle(b.GetHicon());
  13. i.Save(File.Open(@”C:\favicon.ico", FileMode.Create));
Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • LinkedIn
  • Technorati

Leave a Reply

Your email address will not be published. Required fields are marked *