通过Python从png文件生成8位调色板
哪个基于Python的库最适合从给定的.png文件生成8位调色板?就像在Photoshop中生成.pal格式一样。
附注:输入的PNG文件已经是8位格式了。(有调色板)
谢谢!
2 个回答
1
如果你处理的是调色板图像,那么在把它加载到PIL(Python图像库)后,你可以使用getcolors()
这个方法来获取颜色。如果是RGB或RGBA格式的图像,你就需要进行颜色减少,直到最多只剩下256种颜色。
3
我找不到关于.PAL格式的具体说明(Photoshop称它为“Microsoft PAL”),不过这个格式很容易被逆向工程。以下是有效的代码:
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()