这里使用Python win32包中的win32gui.ExtractIconEx方法来提取exe的图标,除了安装Python,还需要到这里下载Pywin。
将指定的a.exe图标保存为bmp格式:
import win32ui import win32gui large, small = win32gui.ExtractIconEx(r"c:/a.exe",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] ) hbmp.SaveBitmapFile( hdc, "save.bmp" )
ExtractIconEx方法返回大32*32,小16*16的两张图标的句柄。后面就根据这个句柄画图保存,这样出来的图片首先不是图标ico格式,其次背景是黑色的很难看。
用PyQt对图像做了处理,使之背景透明,并保持为ico格式。要使用PyQt,请到这里下载PyQt。代码如下:
import sys import win32ui import win32gui from PyQt4 import QtCore from PyQt4 import QtGui class testWindow(QtGui.QMainWindow): def __init__(self): super(testWindow, self).__init__() self.setGeometry(180.0, 130.0, 280.0, 400.0) self.setMouseTracking(True) large, small = win32gui.ExtractIconEx(r"C:/a.exe", 0) win32gui.DestroyIcon(small[0]) self.pixmap = QtGui.QPixmap.fromWinHBITMAP(self.bitmapFromHIcon(large[0]), 2) self.pixmap.save("a.ico","ico") def bitmapFromHIcon(self, hIcon): hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, 32, 32) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), hIcon) hdc.DeleteDC() return hbmp.GetHandle() def paintEvent(self, event): painter = QtGui.QPainter() painter.begin(self) painter.setRenderHint(QtGui.QPainter.Antialiasing) painter.setPen(QtCore.Qt.NoPen) painter.setBrush(QtGui.QBrush(QtGui.QColor(255.0, 255.0, 255.0, 255.0), QtCore.Qt.SolidPattern)) painter.drawRect(QtCore.QRect(0.0, 0.0, 280.0, 400.0)) painter.drawPixmap(QtCore.QRect(0.0, 0.0, 32.0, 32.0), self.pixmap) painter.end() if __name__ == "__main__": app = QtGui.QApplication(sys.argv) mainWindow = testWindow() mainWindow.show() app.exec_()
提取图标和上一份代码是一样的,在得到Bitmap后通过QtGui里的fromWinHBITMAP方法将bitmap转换成透明背景的QPixmap,然后就可以保存为ico格式的图标了。paintEvent方法重写了QMainWindow的方法,画图用而已。