Search code examples
pythonimagewinapipywin328-bit

win32api: get bitmap palette


I'm basically doing this but for 8-bit. I can get the bitmap bits correctly using "P" as the mode bit. However, I have all these bitmap bits, but no palette - PIL just uses a default gray-scale palette. How do I get the correct palette from the image?


Solution

  • This works, returning a PIL-compatible palette:

    import ctypes, win32gui
    def getSystemPalette():
        hwnd = win32gui.GetDesktopWindow()
    
        hwndDC = win32gui.GetWindowDC(hwnd)
    
        buff = ctypes.c_buffer("0"*(256*4)) #R, G, B, and flags
        ctypes.windll.gdi32.GetSystemPaletteEntries(hwndDC, 0, 256, buff)
    
        win32gui.ReleaseDC(hwnd, hwndDC)
    
        #ignore every 4th entry which is the flags
        res = [ord(x) for i,x in enumerate(buff) if i%4 != 3]
        return res