Python 获取 exe 的 icon 并且保存

时间:2023-03-10 02:06:41
Python 获取 exe 的 icon 并且保存

Python 获取 exe 的 icon 并且保存

参考链接:https://mail.python.org/pipermail/python-win32/2009-April/009078.html

import win32ui
import win32gui
import win32con
import win32api #ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
#ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON)
ico_x = 32
ico_y = 32 exePath = "c:/windows/system32/shell32.dll" large, small = win32gui.ExtractIconEx(exePath, 0)
useIcon = large[0]
destroyIcon = small[0]
win32gui.DestroyIcon(destroyIcon) 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), useIcon)
savePath = "d:/test.bmp"
hbmp.SaveBitmapFile(hdc, savePath)

注意:

win32gui.ExtractIconEx 只能提取32x32 和 16x16 的一大一小的图片
hbmp.SaveBitmapFile 只能在已经存在的路径下保存文件,如果路径不存在,用os.makedirs()创建

上面只是保存 bmp,如果想要保存 png,可以给 python 安装 Pillow模块,代码如下:
from PIL import Image
bmpstr = hbmp.GetBitmapBits(True)
img = Image.frombuffer(
'RGBA',
(32,32),
bmpstr, 'raw', 'BGRA', 0, 1
) img.save('icon.png')

Pillow 下载地址:https://pypi.org/project/Pillow/#files

参考链接:https://*.com/questions/32341661/getting-a-windows-program-icon-and-saving-it-as-a-png-python