Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Bitmap to Icon

I'm trying to convert an image from a Bitmap to a Windows icon. This is the code.

private void btnCnvrtSave_Click(object sender, EventArgs e)
{
    Bitmap bmp = (Bitmap)picturePanel.BackgroundImage;
    Bitmap newBmp = new Bitmap(bmp);
    Bitmap targetBmp = newBmp.Clone(new Rectangle(0, 0, newBmp.Width, newBmp.Height), PixelFormat.Format64bppArgb);
    IntPtr Hicon = targetBmp.GetHicon();
    Icon myIcon = Icon.FromHandle(Hicon);

    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Title = "Save Icon";
    sfd.Filter = "Icon|*.ico";
    sfd.ShowDialog();

    FileStream fileStream = new FileStream(sfd.FileName,FileMode.OpenOrCreate);
    myIcon.Save(fileStream);
    fileStream.Flush();
    fileStream.Close();

    MessageBox.Show("Image is converted successfully!");
}

The code is working fine but the problem is, when I convert the picture to an icon the converted icon loses its true colors and gradients (shown in image). So, is there any way by which I can convert the image without losing its colors?

This is what my icon looks like.

Before and after converting

like image 227
kakarott Avatar asked Jul 24 '12 19:07

kakarott


1 Answers

This is a known issue with .Net since it doesn't have an icon encoder. See the following for possible workarounds.

Create Valid Icon Files

Convert Bitmap to Icon problem

like image 186
Gambit Avatar answered Sep 22 '22 18:09

Gambit