Skip to content

Instantly share code, notes, and snippets.

@scriptingstudio
Last active August 16, 2026 20:18
Show Gist options
  • Select an option

  • Save scriptingstudio/765cc31814c557e8b438cc6b302b6800 to your computer and use it in GitHub Desktop.

Select an option

Save scriptingstudio/765cc31814c557e8b438cc6b302b6800 to your computer and use it in GitHub Desktop.
ICO reader in Python demo
import struct
import ctypes
import re
user32 = ctypes.WinDLL(r'C:\Windows\System32\user32.dll')
icofile = r'<filepath_to_your_icofile>' # set your file name!!!
print(icofile)
with open(icofile, 'rb') as f:
data = f.read()
print(len(data)) # validation: must be > 6
# https://en.wikipedia.org/wiki/ICO_(file_format)
# ICONDIRENTRY structure - 16 bytes
# 0 - width
# 1 - height
# 2 - colors
# 6-7 - bits per pixel
# 8-11 - size of image data
# 12-15 - offset of image data
ICONDIRENTRY = '@BBBBHHII'
ICOHEADER = '@IH'
isignature,icount = struct.unpack(ICOHEADER, data[0:6])
print(isignature == 0x10000) # ICO format validation
print(icount) # icon amount
icons = [] # icon storage
diroffset = range(6,16*icount,16)
for k,i in enumerate(diroffset):
w,h,colors,_,_,bpp,l,dataoffset = struct.unpack(ICONDIRENTRY, data[i:i+16])
if 0 == w : w = 256
if 0 == h : h = 256
imgbytes = data[dataoffset:(dataoffset+l)]
hicon = user32.CreateIconFromResourceEx(imgbytes, l, True, 0x30000, w, h, 0)
icons.append({
"Handle" : hicon, # pri ID for an icon
"Index" : k,
"Width" : w,
"Height" : h,
"Colors" : colors,
"Bpp" : bpp,
"Length" : l,
"Bytes" : imgbytes
})
#print(icons)
# simple output formatter
if (len(icons) > 0):
header = " Handle","Index","Width","Height","Colors","Bpp","Length"
hdelim = [re.sub('\S', '-', n) for n in header]
print(" ".join(header))
print(" ".join(hdelim))
fmt = "{0:>{1}}"
for i in icons:
print(
fmt.format(i['Handle'],10),
fmt.format(i['Index'],5),
fmt.format(i['Width'],5),
fmt.format(i['Height'],6),
fmt.format(i['Colors'],6),
fmt.format(i['Bpp'],3),
fmt.format(i['Length'],6)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment