1

I would like to know if it is possible to convert a PNG or JPEG image file to an Icon file (.ico) by using C#. So far the code I am trying to use has failed me. After converting the file, the converted Icon file is corrupted while trying to use it in other softwares that are compatible with Icon (.ico) files. Or when I try to view it in Windows Photo Gallery, it is corrupted. I don't know what I am doing wrong but here is my code:

    private void btnConvert_Click(object sender, EventArgs e)
    {
        Bitmap Cbitmap = null;
        try
        {
            Cbitmap = new Bitmap(@"C:\Users\Landon\Pictures\image.png"); //(32, 32, PixelFormat.Format64bppPArgb);
        }
        catch(Exception)
        {
            MessageBox.Show("Error opening given Image file", "File Error",
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return;
        }
        Cbitmap.MakeTransparent(Color.Transparent);
        System.IntPtr icH = Cbitmap.GetHicon();
        Icon ico = Icon.FromHandle(icH);
        Cbitmap.Dispose();
        System.IO.FileStream f = new System.IO.FileStream(@"C:\Users\Landon\Pictures\" + "\\image.ico", System.IO.FileMode.OpenOrCreate);
        ico.Save(f);
        MessageBox.Show("Image is converted to ICON and saved in the directory: " + @"C:\Users\Landon\Pictures\" + " with name image.ico"); 
    }

If for some reason I am unclear in what I am trying to ask let me know and I will edit my question. For now I have honestly tried my best. All comments are appreciated.

Landon Conway
  • 49
  • 1
  • 6
  • 3
    I wrote code to do this and posted it in an SO answer. But it disappeared, no idea what might have happened. It got copied several times though so it isn't lost, [here is one](http://stackoverflow.com/a/11448060/17034). – Hans Passant Nov 07 '15 at 10:22

0 Answers0