How to extract the icon from a . exe file using python?

Asked

Viewed 123 times

2

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

1 answer

3


According to that 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:

inserir a descrição da imagem aqui


If you want to better understand how it works, I suggest you go into the documentation of the imported libraries and see what methods are used:

  • win32api

    • .GetSystemMetrics()
  • win32con

    • .SM_CXICON()

    • .SM_CYICON()

  • win32gui

    • .ExtractIconEx()

    • .DestroyIcon()

  • win32ui

    • .CreateDCFromHandle()

    • .CreateBitmap()

    • .CreateCompatibleBitmap()

    • .CreateCompatibleDC()

    • .SelectObject()

    • .DrawIcon()

    • .SaveBitmapFile()


To convert the generated image to .bmp for .ico, you can use the Pillow, as in this example:

Code:

from PIL import Image

filename = 'icon.bmp'

img = Image.open(filename)

img.save('logo.ico')

Output:

inserir a descrição da imagem aqui

  • In this case you created an image in bitmap format... you can use this format as icon?

  • I changed my answer, take a look.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.