I have PNG images which I need to convert to an icon before displaying it.
This is how I did it:
public Icon ImageToIcon(Image imgTest)
{
Bitmap bitmap = new Bitmap(imgTest);
Icon icoTest;
IntPtr iPtr = bitmap.GetHicon();
icoTest = (Icon) Icon.FromHandle(iPtr).Clone();
return icoTest;
}
I lose transparency after doing this, alpha transparent images are not rendered as expected....can this be solved?
No, there's a lot more to it. Icons have a pretty elaborate internal structure, optimized to work reasonably on 1980s hardware. An icon image has three bitmaps, one for the icon, a monochrome bitmap that indicates what parts of the image are transparent and another monochrome bitmap that indicates what parts are reversed. Generating those monochrome bitmaps is pretty painful, .NET doesn't support them. Nor does Bitmap.GetHicon() make an attempt at it. You'll need a library to do the work for you.
Vista gave some relief, it started supporting icons that contain a PNG image. You'll have a shot at generating it with your own code. Like this:
Tested on .NET 4.5 and Windows 8.1. Beware of the possibility of "fringes" you'll see on PNG images with transparency on the edges. That only works well when the image is displayed on a well-known background color. Which, by design, an icon can never depend on. A dedicated icon editor will always be the only truly good way to get good looking icons.