0

Let's just say that is have a handle to an icon image in C#. Is there a way, to save the contents as a valid ICO file on disk? I have tried everything but no luck.

The first solution i thought was to create a Bitmap object based on the icon handle, and then save this Bitmap, to file as ico. The problem is that the implementation of .net does not work, and just outputs plain PNG data.

Then i tried implementing the encoder myself. Based on the header description of the ICO container, i implemented this, and works like a charm but only if i use png data as the payload.

If i use bitmap data(which is what is want) the output file does not get recognized by the OS as valid .ico file.

I am 99% sure that the problem is the way i write the bitmap data to the ICO container.

Based on an article i found that when the format in the ico file is PNG image it must be written along with the PNG header. If it is a bitmap image one must only write the raw data of the bitmap without the bitmap header.

Well, what i tried is to get the bitmap data (as byte array) using Lockbits() function of the Bitmap object and write, those after the ico header, and saving the file. I am sure that i had written the headers correctly. But i think that i am missing something, else

What is the correct way to write bitmap data to ico file?? Also, i wonder if there is another solution to write contents of an HICON(INtPtr in C#) handle to ico file.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user969245
  • 83
  • 1
  • 1
  • 8
  • 1
    I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Nov 21 '12 at 00:11
  • You have to pinvoke GetIconInfoEx(). Writing the file from the data is little joy and there's no png support. This normally only ever goes one way, file to icon. – Hans Passant Nov 21 '12 at 00:38

1 Answers1

0

.ico files are not Bitmap files (some programs treat them the same, but they're masking the differences from the user).

An .ico icon file contains the ICO header, but also a "directory" containing entries for each sub-image of the icon. Each sub-image is then a bitmap object (with the Win32 Bitmap header, but not the Win32 Bitmap file header, yes it's confusing).

There's some open-source code that demonstrates ico handling on CodePlex here: http://anolis.codeplex.com/SourceControl/changeset/view/69709#930335 (look at the Save method).

Dai
  • 141,631
  • 28
  • 261
  • 374