How to extract the icon of an .exe file using python?

2

I simply had the need to have a .ico image file extracted from an .exe file and I do not even know how to start it. How can I do this?

    
asked by anonymous 14.04.2017 / 21:59

1 answer

3

According to this answer , you can use the code below. I tested it here and it worked perfectly.

Code:

import win32ui
import win32gui
import win32con
import win32api

ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)

large, small = win32gui.ExtractIconEx("C:\Program Files (x86)\foobar2000\foobar2000.exe",0)
win32gui.DestroyIcon(small[0])

hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x)
hdc = hdc.CreateCompatibleDC()

hdc.SelectObject(hbmp)
hdc.DrawIcon((0,0), large[0])

hbmp.SaveBitmapFile( hdc, 'icon.bmp')

Output:

Ifyouwanttobetterunderstandhowitworks,Isuggestyougointothedocumentationfortheimportedlibrariesandseewhatmethodsareused:

  • win32api

    • .GetSystemMetrics()
  • win32con

    • .SM_CXICON()

    • .SM_CYICON()

  • win32gui

    • .ExtractIconEx()

    • .DestroyIcon()

  • win32ui

    • .CreateDCFromHandle()

    • .CreateBitmap()

    • .CreateCompatibleBitmap()

    • .CreateCompatibleDC()

    • .SelectObject()

    • .DrawIcon()

    • .SaveBitmapFile()

Toconvertthegeneratedimageto.bmpto.ico,youcanuse Pillow , as in this example:

Code:

from PIL import Image

filename = 'icon.bmp'

img = Image.open(filename)

img.save('logo.ico')

Output:

    
14.04.2017 / 22:54