Search code examples
c#imagevisual-studio-2010iconswindows-xp

Image to Icon conversion


I am using following code to convert an image to Icon. Here is my code.

Bitmap Cbitmap=null;
  try
  {
  Cbitmap = new Bitmap("path of local image"); 
  }
  catch(Exception)
  {
  return;
  }
  Cbitmap.MakeTransparent(Color.White);
  System.IntPtr icH = Cbitmap.GetHicon();
  Icon ico = Icon.FromHandle(icH);
  Cbitmap.Dispose();
  System.IO.FileStream f = new System.IO.FileStream(Path where to save icon"" + "\\image.ico", System.IO.FileMode.OpenOrCreate);
  ico.Save(f);
   f.close();
  ico.dispose();

Now this is converted to Icon successfully but when I try to open it in image viewer it shows preview not available.

Also when to try to open it in project it says

(image.ico is not an icon file)


Solution

  • Your code is fine. It converts a JPG to an Icon. What's the dimensions of your original JPG? If they aren't one of the standard icon sizes, you'll get a strange behavior. If the original JPG is too large, you'll get the error you are seeing.

    Some of the more common sizes are 16x16, 24x24, 32x32, 48x48.