Search code examples
pythonfileiconsfile-type

Get Associated Filetype Icon for a File


What I Want

I'm trying to write a function which takes in a filename and returns the icon of the application that is associated with the file's filetype on my system (which is Windows 7).

What I've Tried

I've seen this question, but the answer isn't giving me the details I need. I'm not very familiar with the ctypes module and I find the docs on the VC++ functions difficult to follow.

I also saw this question, but I get stuck on the first hurdle. When I try:

import _winreg
_winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\Microsoft\CurrentVersion\Explorer\FileExts')

It raises a WindowsError: [Error 2] The system cannot find the file specified

Even when I do

_winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\Microsoft')

Which returns a PyHKEY object, any 'key' action I try perform on it raises a TypeError: The object is not a PyHKEY object


Solution

  • I've found an answer here

    the code from the link is:

    import win32ui
    import win32gui
    import win32con
    import win32api
    import cStringIO
    import Image
    
    tempDirectory = os.getenv("temp")
    ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
    
    dst = cStringIO.StringIO()
    
    large, small = win32gui.ExtractIconEx(path,0)
    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 )
    
    #draw a icon in it
    hdc.DrawIcon( (0,0), large[0] )
    win32gui.DestroyIcon(large[0])
    
    #convert picture
    hbmp.SaveBitmapFile( hdc, tempDirectory + "\Icontemp.bmp")
    
    im = Image.open(tempDirectory + "\Icontemp.bmp")
    im.save(dst, "JPEG")
    
    dst.seek(0)
    
    os.remove(tempDirectory + "\Icontemp.bmp")    
    return dst.read()