Search code examples
pythonpngpalettecolor-palette

Generation of 8 bit palette from png file via Python


What would be the best python based library for generating 8-bit palette from the given .png file. As in photoshop generating under .pal format.

PS: Input PNG is already in 8 bit format. (paletted)

Regards


Solution

  • I've not been able to find a spec for .PAL (Photoshop calls it "Microsoft PAL"), but the format is easily reverse-engineered. This works:

    def extractPalette(infile,outfile):
        im=Image.open(infile)
        pal=im.palette.palette
        if im.palette.rawmode!='RGB':
            raise ValueError("Invalid mode in PNG palette")
        output=open(outfile,'wb')
        output.write('RIFF\x10\x04\x00\x00PAL data\x04\x04\x00\x00\x00\x03\x00\x01') # header
        output.write(''.join(pal[i:i+3]+'\0' for i in range(0,768,3))) # convert RGB to RGB0 before writing 
        output.close()