def extract_icon(exefilename): """Get the first resource icon from win32 exefilename and returns it a s PNG bytes array""" ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) large, small = win32gui.ExtractIconEx(exefilename,0) temp_dir = tempfile.mkdtemp() try: 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] ) bmp_temp = os.path.join(temp_dir,"icon.bmp") hbmp.SaveBitmapFile(hdc,bmp_temp) im = Image.open(bmp_temp) png_temp = os.path.join(temp_dir,"icon.png") with open(png_temp,'wb') as png: im.save(png, "PNG") result = open(png_temp,'rb').read() return result finally: win32gui.DestroyIcon(small[0]) win32gui.DestroyIcon(large[0]) if os.path.isdir(temp_dir): shutil.rmtree(temp_dir)
def icon_from_exec_win(self, path): large, small = win32gui.ExtractIconEx(path, 0) for i in small: win32gui.DestroyIcon(i) pixmap = QtWin.fromHBITMAP(self.bitmapFromHIcon(large[0]), 1) for i in large: win32gui.DestroyIcon(i) return QtGui.QIcon(pixmap)
def _SetupList(self): child_style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER | win32con.WS_HSCROLL | win32con.WS_VSCROLL child_style |= commctrl.LVS_SINGLESEL | commctrl.LVS_SHOWSELALWAYS | commctrl.LVS_REPORT self.hwndList = win32gui.CreateWindow("SysListView32", None, child_style, 0, 0, 100, 100, self.hwnd, IDC_LISTBOX, self.hinst, None) child_ex_style = win32gui.SendMessage( self.hwndList, commctrl.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0) child_ex_style |= commctrl.LVS_EX_FULLROWSELECT win32gui.SendMessage(self.hwndList, commctrl.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, child_ex_style) # Add an image list - use the builtin shell folder icon - this # demonstrates the problem with alpha-blending of icons on XP if # winxpgui is not used in place of win32gui. il = win32gui.ImageList_Create( win32api.GetSystemMetrics(win32con.SM_CXSMICON), win32api.GetSystemMetrics(win32con.SM_CYSMICON), commctrl.ILC_COLOR32 | commctrl.ILC_MASK, 1, # initial size 0) # cGrow shell_dll = os.path.join(win32api.GetSystemDirectory(), "shell32.dll") large, small = win32gui.ExtractIconEx(shell_dll, 4, 1) win32gui.ImageList_ReplaceIcon(il, -1, small[0]) win32gui.DestroyIcon(small[0]) win32gui.DestroyIcon(large[0]) win32gui.SendMessage(self.hwndList, commctrl.LVM_SETIMAGELIST, commctrl.LVSIL_SMALL, il) # Setup the list control columns. lvc = LVCOLUMN(mask=commctrl.LVCF_FMT | commctrl.LVCF_WIDTH | commctrl.LVCF_TEXT | commctrl.LVCF_SUBITEM) lvc.fmt = commctrl.LVCFMT_LEFT lvc.iSubItem = 1 lvc.text = "Title" lvc.cx = 200 win32gui.SendMessage(self.hwndList, commctrl.LVM_INSERTCOLUMN, 0, lvc.toparam()) lvc.iSubItem = 0 lvc.text = "Order" lvc.cx = 50 win32gui.SendMessage(self.hwndList, commctrl.LVM_INSERTCOLUMN, 0, lvc.toparam()) win32gui.UpdateWindow(self.hwnd)
def save_icon(icon_path, save_path): if icon_path == "Error: No path found": return False icon_path = icon_path.replace("\\", "/") try: iconX = win32api.GetSystemMetrics(win32con.SM_CXICON) iconY = win32api.GetSystemMetrics(win32con.SM_CXICON) large, small = win32gui.ExtractIconEx(icon_path, 0) win32gui.DestroyIcon(small[0]) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, iconX, iconX) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), large[0]) bmpstr = hbmp.GetBitmapBits(True) from PIL import Image img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1) extrema = img.convert("L").getextrema() if "Chrome" in icon_path: pass # print("TEST") if extrema[1] < 250: img.save(save_path) return True except Exception as e: # print("Error:") # print(e) return False
def get_icon(filepath: Optional[str], icon_save_directory: Optional[str] = None) -> Optional[str]: if not filepath: return None # no file path to save the icon from # TODO: Get icons of different sizes. small, large = win32gui.ExtractIconEx(filepath, 0, 10) if len(large) <= 0: return None # no icon to extract if len(small) > 0: win32gui.DestroyIcon(small[0]) # get rid of the small one hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_y) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), large[0]) executable_path = Path(filepath) icon_path = icon_name = f"icon_{executable_path.name}.bmp" if icon_save_directory: icon_path = str((Path(icon_save_directory) / icon_name).resolve()) hbmp.SaveBitmapFile(hdc, icon_path) with Image.open(icon_path) as img: buffered = BytesIO() img.save(buffered, format="PNG") image_string = base64.b64encode(buffered.getvalue()).decode() if not icon_save_directory: Path(icon_path).unlink() return image_string
def get_icon(PATH, size): SHGFI_ICON = 0x000000100 SHGFI_ICONLOCATION = 0x000001000 if size == "small": SHIL_SIZE = 0x00001 elif size == "large": SHIL_SIZE = 0x00002 else: raise TypeError( "Invalid argument for 'size'. Must be equal to 'small' or 'large'") ret, info = shell.SHGetFileInfo( PATH, 0, SHGFI_ICONLOCATION | SHGFI_ICON | SHIL_SIZE) hIcon, iIcon, dwAttr, name, typeName = info ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) 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), hIcon) win32gui.DestroyIcon(hIcon) bmpinfo = hbmp.GetInfo() bmpstr = hbmp.GetBitmapBits(True) img = Image.frombuffer("RGBA", (bmpinfo["bmWidth"], bmpinfo["bmHeight"]), bmpstr, "raw", "BGRA", 0, 1) if size == "small": img = img.resize((16, 16), Image.ANTIALIAS) return img
def test(exePath): 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) print('dd', (useIcon)) 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)
def __init__(self): message_map = { win32con.WM_DESTROY: self.on_destroy, win32con.WM_COMMAND: self.on_command, win32con.WM_USER + 20: self.on_taskbar_notify } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "TimeCounter" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow(classAtom, "Taskbar", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) # icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE try: shell_dll = os.path.join(win32api.GetSystemDirectory(), "shell32.dll") large, small = win32gui.ExtractIconEx(shell_dll, 265, 1) hicon = small[0] win32gui.DestroyIcon(large[0]) except: hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP nid = (self.hwnd, 0, flags, win32con.WM_USER + 20, hicon, "Starting...") win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid) global handel handel = self.hwnd
def __init__(self): iconEmbededM = 0 numberOfFilesM = 0 fileListM = self.dir_list('E:\\Users\\tigerlyb\\Documents\\CSCI8260Project\\malware\\') for f in fileListM: if f != 'E:\\Users\\tigerlyb\\Documents\\CSCI8260Project\\malware\\.DS_Store': numberOfFilesM = numberOfFilesM + 1 print "File Number(Malware): ", numberOfFilesM print f if win32gui.ExtractIconEx(f, -1): print "Icon Embedded(Malware)." print "" iconEmbededM = iconEmbededM + 1 large, small = win32gui.ExtractIconEx(f, 0) print win32gui.ExtractIconEx(f, 0) win32gui.DestroyIcon(small[0]) self.pixmap = QtGui.QPixmap.fromWinHBITMAP(self.bitmapFromHIcon(large[0]), 2) dest = "C:\\Users\\tigerlyb\\Documents\\PE\\iconM\\" + f[52:len(f)-4] + ".ico" self.pixmap.save(dest) else: print "No Icon Embedded(Malware)." print "" print "" print "Total Number Of Files Embedded Icon(Malware): ", iconEmbededM
def __init__(self): iconEmbededN = 0 numberOfFilesN = 0 fileListN = self.dir_list( 'C:\\Users\\tigerlyb\\Documents\\PE\\normal\\') for f in fileListN: numberOfFilesN = numberOfFilesN + 1 print "File Number(NormalFile): ", numberOfFilesN print f if win32gui.ExtractIconEx(f, -1): print "Icon Embedded(NormalFile)." iconEmbededN = iconEmbededN + 1 large, small = win32gui.ExtractIconEx(f, 0) print large[0], small[0] print win32gui.ExtractIconEx(f, 0) win32gui.DestroyIcon(small[0]) self.pixmap = QtGui.QPixmap.fromWinHBITMAP( self.bitmapFromHIcon(large[0]), 2) dest = "C:\\Users\\tigerlyb\\Documents\\PE\\iconN\\" + f[ 42:len(f) - 4] + ".ico" self.pixmap.save(dest) print "" else: print "No Icon Embedded(NormalFile)." print "" print "" print "Total Number Of Files Embedded Icon(NormalFile): ", iconEmbededN
def IconToFile(hlib, tmpDirName, group_name): libc = ctypes.CDLL(ctypes.util.find_library('c')) libc.memcpy.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t] libc.memcpy.restype = ctypes.c_char_p # patch FindResourceW, ctypes.windll.kernel32.SizeofResource FindResourceW = ctypes.windll.kernel32.FindResourceW FindResourceW.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p ] FindResourceW.restype = ctypes.c_void_p SizeofResource = ctypes.windll.kernel32.SizeofResource SizeofResource.argtypes = [ctypes.c_void_p, ctypes.c_void_p] SizeofResource.restype = ctypes.c_size_t hRes = win32api.LoadResource(hlib, win32con.RT_GROUP_ICON, group_name) mem_icon_dir = ctypes.windll.kernel32.LockResource(hRes) # 32 bits color; 16 and 256 colors are too old icon_size = 256 icon_name = ctypes.windll.user32.LookupIconIdFromDirectoryEx( mem_icon_dir, True, icon_size, icon_size, 0x00000000) sys.stderr.write("icon_name=%s\n" % str(icon_name)) hResInfo = FindResourceW(hlib, icon_name, win32con.RT_ICON) size = ctypes.windll.kernel32.SizeofResource(hlib, hResInfo) rec = win32api.LoadResource(hlib, win32con.RT_ICON, icon_name) mem_icon = ctypes.windll.kernel32.LockResource(rec) # And this is some differ (copy data to Python buffer) binary_data = (ctypes.c_ubyte * size)() libc.memcpy(binary_data, mem_icon, size) hIconRet = ctypes.windll.user32.CreateIconFromResourceEx( binary_data, size, True, 0x00030000, 0, 0, 0x00000000) info = win32gui.GetIconInfo(hIconRet) bminfo = win32gui.GetObject(info[4]) # generate bitmap by drawing the icon hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, bminfo.bmWidth, bminfo.bmHeight) hcdc = hdc.CreateCompatibleDC() hcdc.SelectObject(hbmp) win32gui.DrawIconEx(hcdc.GetHandleOutput(), 0, 0, hIconRet, bminfo.bmWidth, bminfo.bmHeight, 0, 0, 0x0003) # Need temp directory or generate image on the fly, for inclusion into an HTML page. # Temp file visible from HTTP server. # An alternative is to send the file content to a socket stream. # MIME type is "image/bmp" imgFilNam = "icon-%03dx%03d-%05d-%03d.bmp" % ( bminfo.bmWidth, bminfo.bmHeight, group_name, icon_name) if tmpDirName: imgFilNam = tmpDirName + imgFilNam sys.stderr.write("Generating %s\n" % imgFilNam) hbmp.SaveBitmapFile(hcdc, imgFilNam) win32gui.DestroyIcon(hIconRet) return imgFilNam
def IconToFile(hlib, group_name): """The group might be a string or an integer and its type must be kept.""" # patch FindResourceW, ctypes.windll.kernel32.SizeofResource FindResourceW = ctypes.windll.kernel32.FindResourceW FindResourceW.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p ] FindResourceW.restype = ctypes.c_void_p SizeofResource = ctypes.windll.kernel32.SizeofResource SizeofResource.argtypes = [ctypes.c_void_p, ctypes.c_void_p] SizeofResource.restype = ctypes.c_size_t hRes = win32api.LoadResource(hlib, win32con.RT_GROUP_ICON, group_name) mem_icon_dir = ctypes.windll.kernel32.LockResource(hRes) # 32 bits color; 16 and 256 colors are too old icon_size = 256 icon_name = ctypes.windll.user32.LookupIconIdFromDirectoryEx( mem_icon_dir, True, icon_size, icon_size, 0x00000000) h_res_info = FindResourceW(hlib, icon_name, win32con.RT_ICON) size = ctypes.windll.kernel32.SizeofResource(hlib, h_res_info) rec = win32api.LoadResource(hlib, win32con.RT_ICON, icon_name) mem_icon = ctypes.windll.kernel32.LockResource(rec) # And this is some differ (copy data to Python buffer) binary_data = (ctypes.c_ubyte * size)() ctypes.memmove(binary_data, mem_icon, size) h_icon_ret = ctypes.windll.user32.CreateIconFromResourceEx( binary_data, size, True, 0x00030000, 0, 0, 0x00000000) info = win32gui.GetIconInfo(h_icon_ret) bminfo = win32gui.GetObject(info[4]) # generate bitmap by drawing the icon hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, bminfo.bmWidth, bminfo.bmHeight) hcdc = hdc.CreateCompatibleDC() hcdc.SelectObject(hbmp) win32gui.DrawIconEx(hcdc.GetHandleOutput(), 0, 0, h_icon_ret, bminfo.bmWidth, bminfo.bmHeight, 0, 0, 0x0003) # MIME type is "image/bmp" # The group name might be a number: 110 etc... or a string such as 'ICO_MYCOMPUTER'. # This is the prefix of the temporary BMP file name containing the extracted icon. img_fil_nam_prefix = "icon-%03dx%03d-%s-%03d" % ( bminfo.bmWidth, bminfo.bmHeight, str(group_name), icon_name) # The destructor will remove the file. obj_temp_file = lib_util.TmpFile(img_fil_nam_prefix, "bmp") img_fil_nam = obj_temp_file.Name hbmp.SaveBitmapFile(hcdc, img_fil_nam) win32gui.DestroyIcon(h_icon_ret) return obj_temp_file
def make_icon(self, link_path, save_path): """获取exe文件的图标""" if os.path.splitext(link_path)[-1].lower() == ".exe": # 此处程序后缀有可能为大写的EXE large, small = win32gui.ExtractIconEx(link_path, 0) win32gui.DestroyIcon(small[0]) self.pixmap = QtGui.QPixmap.fromWinHBITMAP(self.__bitmap_from_hIcon(large[0]), 2) self.pixmap.save(save_path, "ico") return True else: return False
def dispalyName_Icon(self): i = 0 for key in self.numreg[1].keys(): try: # ico 来自exe ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) large, small = win32gui.ExtractIconEx( self.numreg[1][key]['exe'], 0) #exemenu=self.numreg[1][key]['exe'] useIcon = large[0] destroyIcon = small[0] win32gui.DestroyIcon(destroyIcon) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_y) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), useIcon) #savePath = "d:/test.bmp" #savePath = "d:/" #hbmp.SaveBitmapFile(hdc, savePath) bmpstr = hbmp.GetBitmapBits(True) img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1) cwd = os.getcwd() img.save(cwd + '/icon.png') self.pixmap = 'icon.png' #except Exception as e: #ico 来自 icon except: #ico 来自 icon # 判断ico文件是否存在 if 'icon' in self.numreg[1][key] and os.path.isfile( self.numreg[1][key]['icon']): self.pixmap = QPixmap(self.numreg[1][key]['icon']) iconMenu = self.numreg[1][key]['icon'] #split = iconMenu.split('\\') #exeMenu ='\\'.join(split[:-1]) else: # 不存在ico文件给定默认图标 self.pixmap = 'SoftwareTool.png' #exeMenu = '' DisplayName = self.numreg[1][key]['DisplayName'].encode('utf-8') DisplayName = str(DisplayName, encoding='utf-8') newitem = QTableWidgetItem(QIcon(self.pixmap), DisplayName) #newitem1 = QTableWidgetItem(filesize) #为每个表格内添加数据 self.tableWidget.setItem(i, 0, newitem) #self.tableWidget.setItem(i,1,newitem1) i += 1
def get_icon(exe): ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) large, small = win32gui.ExtractIconEx(exe, 0) if len(small) == 0: return False win32gui.DestroyIcon(large[0]) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) icon_bmp = win32ui.CreateBitmap() icon_bmp.CreateCompatibleBitmap(hdc, ico_x, ico_y) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(icon_bmp) hdc.DrawIcon((0, 0), small[0]) # draw the icon before getting bits icon_info = icon_bmp.GetInfo() icon_buffer = icon_bmp.GetBitmapBits(True) icon = Image.frombuffer('RGB', (icon_info['bmWidth'], icon_info['bmHeight']), icon_buffer, 'raw', 'BGRX', 0, 1) win32gui.DestroyIcon(small[0]) return icon
def _init_from_image_and_hotspot(self, image, hotspot): #print "Cursor._init_from_image_and_hotspot:" ### hicon = image._win_image.GetHICON() iconinfo = gui.GetIconInfo(hicon) gui.DestroyIcon(hicon) flag, xhot, yhot, hbmMask, hbmColor = iconinfo xhot, yhot = hotspot cursorinfo = (True, xhot, yhot, hbmMask, hbmColor) win_cursor = gui.CreateIconIndirect(cursorinfo) gui.DeleteObject(hbmMask) gui.DeleteObject(hbmColor) self._win_cursor = win_cursor
def get_icon(self): try: icons_large, icons_small = win32gui.ExtractIconEx(self.path, 0) except pywintypes.error: logger.warning('ExtractIconEx failed: title={}, path={}'.format( repr(self.title), self.path)) return QPixmap() icons = icons_large + icons_small if not icons: logger.warning('no icons: {}'.format(self.path)) return QPixmap() pixmap = hicon2pixmap(icons[0]) for hicon in icons: win32gui.DestroyIcon(hicon) return pixmap
def saveExecutableIcon(exe, out="tmp/icon.png"): shell = win32com.client.Dispatch("WScript.Shell") ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) large, small = win32gui.ExtractIconEx(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, out) img = Image.open(out) img.save(out, 'png')
def read_icon(handle, icon): must_use_qt() resource = win32api.LoadResource(handle, win32con.RT_ICON, icon.id) pixmap = QPixmap() pixmap.loadFromData(resource) hicon = None if pixmap.isNull(): if icon.width > 0 and icon.height > 0: hicon = ctypes.windll.user32.CreateIconFromResourceEx( resource, len(resource), True, 0x00030000, icon.width, icon.height, win32con.LR_DEFAULTCOLOR) else: hicon = win32gui.CreateIconFromResource(resource, True) pixmap = hicon_to_pixmap(hicon).copy() win32gui.DestroyIcon(hicon) return pixmap
def windowsIconGetter(path, nIcon=0, exeOrDll=True): #It's can be exe, dll, or already ico if os.path.isfile(path): dst = cStringIO.StringIO() if exeOrDll: large, small = win32gui.ExtractIconEx(path, nIcon) win32gui.DestroyIcon(small[0]) #creating a destination memory DC hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) #set the background in white hdc.FillSolidRect((0, 0, ico_x, ico_x), 0xffffff) #draw a icon in it hdc.DrawIcon((0, 0), large[0]) win32gui.DestroyIcon(large[0]) #convert picture in JPEG hbmp.SaveBitmapFile(hdc, dirTmpFile) im = Image.open(dirTmpFile) else: im = Image.open(path) try: im.save(dst, "JPEG") except IOError: return None dst.seek(0) return base64.b64encode(dst.read()) else: return None
def prep(self): ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON) lr, sm = win32gui.ExtractIconEx(self.executable,0) win32gui.DestroyIcon(lr[0]) hicon = sm[0] hdcBitmap = win32gui.CreateCompatibleDC(0) hdcScreen = win32gui.GetDC(0) hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y) hbmOld = win32gui.SelectObject(hdcBitmap, hbm) brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU) win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush) win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL) win32gui.SelectObject(hdcBitmap, hbmOld) win32gui.DeleteDC(hdcBitmap) return hbm
def __init__(self, parent, name, commands=None, icon_path=None): self.parent = parent self.name = name self.WM_NOTIFY = win32con.WM_USER + 20 wndproc = { win32con.WM_DESTROY: self.on_destroy, win32con.WM_COMMAND: self.on_command, self.WM_NOTIFY: self.on_tray_notify, } wc = win32gui.WNDCLASS() wc.hInstance = hinst = win32api.GetModuleHandle(None) wc.lpszClassName = name.title() wc.lpfnWndProc = wndproc try: class_atom = win32gui.RegisterClass(wc) except: pass self.hwnd = win32gui.CreateWindow(wc.lpszClassName, "", win32con.WS_POPUP, 0, 0, 1, 1, 0, 0, hinst, None) win32gui.UpdateWindow(self.hwnd) if icon_path is not None and os.path.isfile(icon_path): icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE hicon = win32gui.LoadImage(None, icon_path, win32con.IMAGE_ICON, 0, 0, icon_flags) else: shell_dll = os.path.join(win32api.GetSystemDirectory(), "shell32.dll") large, small = win32gui.ExtractIconEx(shell_dll, 19, 1) #19 or 76 hicon = small[0] win32gui.DestroyIcon(large[0]) self.hicon = hicon flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP | win32gui.NIF_INFO nid = (self.hwnd, 0, flags, self.WM_NOTIFY, self.hicon, self.name) win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid) self.next_command_id = 1000 self.commands = {} self.register_command('Exit', lambda: win32gui.DestroyWindow(self.hwnd)) if commands is not None: for n, f in commands[::-1]: self.register_command(n, f)
def save_app_icon(app_path, save_path, save_gray_path): large, small = win32gui.ExtractIconEx(app_path, 0) win32gui.DestroyIcon(small[0]) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, 32, 32) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), large[0]) bmpstr = hbmp.GetBitmapBits(True) img = Image.frombuffer( 'RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1 ) img.save(save_path) img = img.convert("LA") img.save(save_gray_path)
def get_icon(path): path = path.replace("/", "\\") ret, info = shell.SHGetFileInfo( path, 0, SHGFI_ICONLOCATION | SHGFI_ICON | SHIL_SIZE) icon, _, _, _, _ = info ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) 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), icon) win32gui.DestroyIcon(icon) bmpinfo = hbmp.GetInfo() bmpstr = hbmp.GetBitmapBits(True) img = Image.frombuffer("RGBA", (bmpinfo["bmWidth"], bmpinfo["bmHeight"]), bmpstr, "raw", "BGRA", 0, 1) return img
def extractExeIcons(exePath, exeName): # desktop = os.path.join(os.environ['USERPROFILE'], "Desktop") iconPath = os.getcwd() + r'\icons' if not os.path.exists(iconPath): os.mkdir(iconPath) try: path = exePath.replace("\\", "/") if "Discord" in path: path = os.environ['USERPROFILE'].replace( "\\", "/") + "/AppData/Local/Discord/app.ico" if "valorant" in path: path = os.environ['systemdrive'].replace( "\\", "/" ) + "/ProgramData/Riot Games/Metadata/valorant.live/valorant.live.ico" if "Teams" in path: path = os.environ['USERPROFILE'].replace( "\\", "/") + "/AppData/Local/Microsoft/Teams/app.ico" icoX = win32api.GetSystemMetrics(win32con.SM_CXICON) icoY = win32api.GetSystemMetrics(win32con.SM_CYICON) large, small = win32gui.ExtractIconEx(path, 0) win32gui.DestroyIcon(small[0]) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, icoX, icoY) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), large[0]) bmpstr = hbmp.GetBitmapBits(True) img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1) new_img_location = iconPath + '\\' + exeName + '.ico' img.save(new_img_location, format("ico")) new_img_location = new_img_location.replace("\\", "/") hbmp.SaveBitmapFile(hdc, iconPath + '\\' + exeName + '.bmp') except: new_img_location = None return new_img_location
def iconextract(path, filename): try: ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) large, small = win32gui.ExtractIconEx(path, 0) win32gui.DestroyIcon(large[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), small[0]) hbmp.SaveBitmapFile(hdc, filename + ".bmp") img = Image.open(filename + ".bmp") img.save(filename + '.ico') for p in Path(".").glob("*.bmp"): p.unlink() except: pass
def __init__(self, parent=None): super(ListDialog, self).__init__(parent) self.contentsWidget = QtGui.QListWidget() self.contentsWidget.setViewMode(QtGui.QListView.IconMode) self.contentsWidget.setIconSize(QtCore.QSize(96, 84)) # Icon 大小 self.contentsWidget.setMovement( QtGui.QListView.Static) # Listview不让列表拖动 self.contentsWidget.setMaximumWidth(800) # 最大宽度 self.contentsWidget.setSpacing(15) # 间距大小 winrege = winregeditor() self.numreg = winrege.getreg() for key in self.numreg.keys(): Atem = QtGui.QListWidgetItem(self.contentsWidget) try: # ico 来自exe large, small = win32gui.ExtractIconEx(self.numreg[key]['exe'], 0) exeMenu = self.numreg[key]['exe'] win32gui.DestroyIcon(small[0]) self.pixmap = QtGui.QPixmap.fromWinHBITMAP( self.bitmapFromHIcon(large[0]), 2) except Exception as err: # ico 来自 icon if self.numreg[key].has_key('icon') and os.path.isfile( self.numreg[key]['icon']): # 判断ico文件是否存在 self.pixmap = QtGui.QPixmap(self.numreg[key]['icon']) iconMenu = self.numreg[key]['icon'] split = iconMenu.split('\\') exeMenu = '\\'.join(split[:-1]) else: # 不存在ico文件给定默认图标 self.pixmap = ':default.png' exeMenu = '' Atem.setIcon(QtGui.QIcon(self.pixmap)) Atem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) Atem.setTextAlignment(QtCore.Qt.AlignHCenter) Atem.setData(QtCore.Qt.UserRole, exeMenu) DisplayName = self.numreg[key]['DisplayName'].encode('utf-8') Atem.setToolTip(u"" + DisplayName) # tip 显示 if len(DisplayName) >= 6: DisplayName = DisplayName.decode('utf8')[0:6].encode( 'utf8') + '…' Atem.setText(u"" + DisplayName)
def getAndWriteProgImage(input_path, output_path): input_path = input_path.replace("\\", "/") icoX = win32api.GetSystemMetrics(win32con.SM_CXICON) icoY = win32api.GetSystemMetrics(win32con.SM_CXICON) large, small = win32gui.ExtractIconEx(input_path, 0) win32gui.DestroyIcon(small[0]) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, icoX, icoX) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), large[0]) bmpstr = hbmp.GetBitmapBits(True) img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1) img.save(output_path)
def get_cursor(hcursor): info = win32gui.GetCursorInfo() hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, 36, 36) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0,0), hcursor) bmpinfo = hbmp.GetInfo() bmpbytes = hbmp.GetBitmapBits() bmpstr = hbmp.GetBitmapBits(True) im = np.array(Image.frombuffer( 'RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1)) win32gui.DestroyIcon(hcursor) win32gui.DeleteObject(hbmp.GetHandle()) hdc.DeleteDC() return im
def __init__(self, cmd, tooltip): self.cmd = cmd message_map = { win32con.WM_DESTROY: self.onDestroy, win32con.WM_COMMAND: self.onCommand, WM_TASKBARNOTIFY: self.onTaskbarNotify, } # Register the Window class. wc = win32gui.WNDCLASS() wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "PythonTaskbarDemo" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow( classAtom, "Taskbar Demo", style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, wc.hInstance, None) win32gui.UpdateWindow(self.hwnd) hProcess, hThread, dwProcessId, dwThreadId = win32process.CreateProcess( None, self.cmd, None, None, 0, 0, None, None, win32process.STARTUPINFO()) self.hProcess = hProcess try: hicon, small = win32gui.ExtractIconEx( win32api.GetModuleFileName(0), 0) win32gui.DestroyIcon(small[0]) #hicon = pywintypes.HANDLE(hicon[0]) hicon = hicon[0] except IndexError: hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) self.hicon = hicon self.tooltip = tooltip self.show()