views:

42

answers:

2

Hello, 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

+1  A: 

If it's a palletted image then you can use the getcolors() method once you have loaded it into PIL. If it's a RGB or RGBA image then you'll need to do color reduction until you have 256 colors at most.

Ignacio Vazquez-Abrams
thanks for the suggestion Ignacio, what about generating a .pal palette version of this method? Regards
Hellnar
I have no idea what that file format looks like. I suspect that you'll need to use `struct` eventually though.
Ignacio Vazquez-Abrams
+1  A: 

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()
works like a charm, thanks foone!
Hellnar