I have the contents of a .ico
file in memory as a const char*
, and I wish to create a HICON
from this data. My current approach is to write the data to a temporary file and then use LoadImage
. Is it possible to instead create the icon directly from memory?

- 6,040
- 8
- 41
- 80
-
Yes. Parse the file and create the icon. – David Heffernan Feb 10 '17 at 19:27
-
@DavidHeffernan I'm trying to avoid creating a file. I have the contents of the icon in memory as a character array and wish to create a HICON directly from that data. – Alex Flint Feb 10 '17 at 19:32
-
1Have a look at `CreateIconFromResource`. – Jonathan Potter Feb 10 '17 at 19:41
-
https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Icon.cs,e01910ea8cd8d6a8 – Hans Passant Feb 10 '17 at 19:42
-
So don't create a file. Parse the content and create the icon. – David Heffernan Feb 10 '17 at 19:59
-
@DavidHeffernan Thanks - my question is about how to do exactly that. – Alex Flint Feb 10 '17 at 20:02
-
1There are plenty of articles on the ico format. Read them and take it from there. – David Heffernan Feb 10 '17 at 20:38
-
3If you can use [GDI+](https://msdn.microsoft.com/en-us/library/ms533798.aspx), you can wrap the raw ICO data in an `IStream` using `CreateStreamOnHGlobal()` or `SHCreateMemStream()`, and then pass that stream to the `Bitmap` class constructor or `Bitmap::FromStream()` method, and then finally call the `Bitmap::ToHICON()` method. – Remy Lebeau Feb 11 '17 at 03:34
2 Answers
With CreateIcon
you can certainly create icons but I'm not really sure you can feed it with a png-format image data.
I had success with CreateIconFromResourceEx (sorry for using other language, but take it as an example, you can use that function directly in C) :
from ctypes import *
from ctypes.wintypes import *
CreateIconFromResourceEx = windll.user32.CreateIconFromResourceEx
size_x, size_y = 32, 32 LR_DEFAULTCOLOR = 0
with open("my32x32.png", "rb") as f:
png = f.read()
hicon = CreateIconFromResourceEx(png, len(png), 1, 0x30000, size_x, size_y, LR_DEFAULTCOLOR)
Hope it helps you.

- 73
- 5
If you want to do this without using GDI+ nor WIC then you have to do some parsing yourself because the format of a .ICO file is not exactly the same as a icon resource in a .EXE/.DLL so you cannot use the resource based icon functions. The official binary spec can be found here and there is a great blog series about it here.
If your .ico file has more than one image in it then you must loop over the icon directories until you find a image dimension you are happy with. You can then call CreateIcon
to create a HICON
.

- 97,548
- 12
- 110
- 164