Link to home
Start Free TrialLog in
Avatar of Realmrat
Realmrat

asked on

Saving a bitmap as an icon.

Hello I was just wondering how I would save a bitmap file as an icon file.  I know how to convert the bitmap to an icon, but I do not know how to save it to disk once it is converted.  Thanks for the help.

Bitmap bmp = new Bitmap("c:\temp\test.bmp");
Icon icon = ImageToIcon(bmp);

// How do I save the icon to disk??

// Convert an image to an Icon
System.Drawing.Icon ImageToIcon(System.Drawing.Image image)
{
    return System.Drawing.Icon.FromHandle(((Bitmap) image).GetHicon());
}

- Joe
Avatar of AlexFM
AlexFM

bmp.Save(@"c:\temp\test.ico", ImageFormat.Icon);
Avatar of Realmrat

ASKER

Thank you Alex ... that appears to work -  though if I try and use the newly saved icon in a project, the program crashes.  Also if you try and edit it within visual studio I get what looks like only a hex representation of the object, instead of being able to edit the Icon (change colors of each pixel).

I am creating the bitmap dynamically, so I suppose that could be it.  I will create a test bitmap with photoshop and see if I get the same error.


- Joe
Try this:

Bitmap bmp = new Bitmap("c:\temp\test.bmp");
Icon icon = ImageToIcon(bmp);
Bitmap bmp1 = Bitmap.FromHicon(icon.Handle);
bmp1.Save(@"c:\temp\test.ico", ImageFormat.Icon);
I regret to inform that this did not work.

In visual studio I tried to change the form icon by clicking on the properties of the form, and browsing to the newly created icon.  I received the error:

The argument 'picture' must be a picture that can be used as a Icon.

Any ideas?

- Joe
Your second suggestion provided the same results.

- Joe
Avatar of Bob Learned
What is the color-depth for the BMP that you are trying to convert?

Bob
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Your solution worked perfectly thanks Bob.

- Joe
Guess I should say I had to change a line or two to get it to compile - but minor changes.  Here's the cut & paste.


public static void BmpToIcon(string sourcePath, string targetPath)
{

            // Retrieve the bitmap from the file.
            Bitmap bmp = (Bitmap)Image.FromFile(sourcePath);

            // Convert the bitmap to an icon.
            Icon ico = Icon.FromHandle(bmp.GetHicon());
   
            // Create a file stream to save the icon stream.
            Stream st = new FileStream(targetPath, FileMode.Create);

            // Create a stream writer to physical write the data to the disk.
            BinaryWriter wr = new BinaryWriter(st);

            // Write the binary icon data to the file stream.
            ico.Save(st);

            // Close the file to write the stream to the disk.
            wr.Close();
}