通过 Python 从 png 文件生成 8 位调色板

发布于 2024-09-08 11:23:54 字数 123 浏览 4 评论 0原文

从给定的 .png 文件生成 8 位调色板的最佳基于 python 的库是什么。 就像在 Photoshop 中生成 .pal 格式一样。

PS:输入 PNG 已经是 8 位格式。 (调色板)

问候

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

壹場煙雨 2024-09-15 11:23:54

我一直无法找到 .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()

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()
濫情▎り 2024-09-15 11:23:54

如果它是调色板图像,则将其加载到 PIL 后可以使用 getcolors() 方法。如果它是 RGB 或 RGBA 图像,那么您需要进行颜色缩减,直到最多有 256 种颜色。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文