lnk文件图标需要找到对应的exe文件所在真实路径才能获取图标,不能够直接获取。dll与没有指定图标的exe文件获取图标会报错。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import win32gui import win32ui from PIL import Image import win32com.client
def pra_lnk(file_path:str): """解析lnk文件""" shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(file_path) return shortcut.Targetpath
def get_ico_from_exe(file_path:str): """获取exe的ico图标""" file_path = pra_lnk(file_path) if ".lnk" in file_path else file_path try: large, small = win32gui.ExtractIconEx(f'{file_path}', 0) useIcon = large[0] destroyIcon = small[0] win32gui.DestroyIcon(destroyIcon) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, 32, 32) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), useIcon) bmpstr = hbmp.GetBitmapBits(True) img = Image.frombuffer( 'RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1 ) img.save('icon.png') except: print("获取图标失败!")
get_ico_from_exe(r"C:\Users\Administrator\Desktop\Synology Chat.lnk")
|