Maybe this is a very easy problem to solve but I haven't found the perfect solution yet. I'm trying to convert a png to ico with C# and found the question converting .PNG to .ICO in C/C# which sort of gives a working solution as below:
using (FileStream stream = File.OpenWrite(@"C:\temp\test.ico"))
{
Bitmap bitmap = (Bitmap)Image.FromFile(@"c:\temp\test.png");
Icon.FromHandle(bitmap.GetHicon()).Save(stream);
}
For my own project I have changed this approach slightly to:
string pngFile = "path/to/pngfile";
using (Bitmap bitmap = new Bitmap(pngFile))
{
using (Icon icon = Icon.FromHandle(bitmap.GetHicon()))
{
using (MemoryStream stream = new MemoryStream())
{
icon.Save(stream);
// something interesting with icon here
}
}
}
The problem that I am experiencing is that the resulting ico is of poor quality, I'm guessing it got resized to 16x16 and lost some of it's color depth, perhaps now only has 16 colors? How can I convert to a higher quality ico file?
I believe you will need a more robust method than GetHIcon()
. It is more of a "quick and dirty" option, and by no means loss-less.
Here's an example of a class that can preserve image quality on the way to converting as ICO: