22

I am trying to convert bitmap into icon. But there is some error as the resultant file is just blank.

private void btnCnvrtSave_Click(object sender, EventArgs e)
{
    Bitmap bmp = new Bitmap(sourceFile);  //sourceFile = openfiledialog.FileName;
    IntPtr Hicon = bmp.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!");

    //Process.Start(sfd.FileName);
}

I've tried a lot to figure-out the problem but couldn't. Please tell me where the problem is.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Muhammad Ali Dildar
  • 1,467
  • 6
  • 24
  • 35

4 Answers4

17

Please, use DestroyIcon after GetHicon, to prevent memory leak

[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

MSDN : https://msdn.microsoft.com/en-us/library/system.drawing.bitmap.gethicon%28v=vs.110%29.aspx

Nigrimmist
  • 10,289
  • 4
  • 52
  • 53
8

This article describes how to convert a bitmap to an icon.

http://www.go4expert.com/forums/showthread.php?t=19250

It looks very similiar to your one:

using (Cbitmap = new Bitmap(sourceImage.Text))
{
    Cbitmap.MakeTransparent(Color.White);
    System.IntPtr icH = Cbitmap.GetHicon();
    Icon ico = Icon.FromHandle(icH);
}
using (System.IO.FileStream f = new System.IO.FileStream(destinationFldr.Text + "\\image.ico", System.IO.FileMode.OpenOrCreate))
{
    ico.Save(f);
}

Try it out.

EDITED: Added the using statements.

Dennis
  • 2,132
  • 3
  • 21
  • 28
6

The only problem with this code is that it supports bitmap images upto 128x128.

It yields a blank ico file if the size of bitmap is greater.

Muhammad Ali Dildar
  • 1,467
  • 6
  • 24
  • 35
2

Also, this SO question links to how to convert an image to an icon, which may lead you in the right direction.

Notice, however, that the code as written needs to be modified to avoid a handle leak. But the solution is also linked in that question.

Community
  • 1
  • 1
Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52