问题描述
我如何检查GIF是否透明(甚至是部分)?
How would I go about checking if a GIF is transparent (even partially)?
我用PNG打开图像并检查图像是用PNG完成的模式。但无论如何,GIF都有相同的模式。
I accomplished this with PNGs by opening the image up with PIL and checking the image's mode. But GIFs have the same mode regardless.
至于误报,我不介意一个完全不透明的GIF被标记为透明(假设这是一种罕见的情况),但我很清楚透明GIF是否被标记为不透明。
As for false positives I don't mind if a completely opaque GIF gets flagged as transparent (assuming this is a rare case), but I do mind if a transparent GIF gets flagged as being opaque.
至于库,我更喜欢使用PIL而不是其他东西的解决方案,但无论如何。
As for libraries, I'd prefer a solution that uses PIL rather than something else, but whatever works.
推荐答案
img = Image.open(filename)
if img.mode == "RGBA" or "transparency" in img.info:
# image uses transparency
请参阅了解透明度如何与GIF配合使用(和8 -bit,palettized,PNGs)。
See here for how transparency works with GIF (and 8-bit, palettized, PNGs).
请注意,您的误报 是可能的:GIF可以将颜色定义为透明但不使用它。我想这可能是非常罕见的 - 为什么抛出一种颜色以获得透明度而不使用它? (你的假阴性是不可能的。)
Note that your false positive case is possible: a GIF could define a color as transparent but not use it. I imagine this would be quite rare, though -- why throw a color away for transparency and not use it? (Your false negative is not possible.)
但是,如果你需要知道是否实际使用透明度,你可以制作两个版本的图像,其中透明色映射到不同的颜色(比如黑色和白色),然后比较它们。如果存在任何差异,则图像确实使用透明度。像这样:
Still, if you need to know whether transparency is actually used, you can make two versions of the image in which the transparent color is mapped to different colors (say, black and white) and then compare them. If there are any differences, the image does use transparency. Like so:
def uses_transparency(filename):
img = Image.open(filename)
trans = img.info.get("transparency", None)
if trans is not None:
trans *= 3 # convert color number to palette table index
palette = img.getpalette()
imgs = []
for bg in [0, 255]: # map transparent color first to black, then white
palette[trans:trans+3] = [bg] * 3
img.putpalette(palette)
imgs.append(img.convert("L"))
return bool(ImageChops.difference(*imgs).getbbox())
您可以使用类似的方法来查看24位PNG是否实际使用alpha通道,将其粘贴到白色和黑色背景并比较结果。
You could use a similar approach to see whether a 24-bit PNG actually uses the alpha channel, by pasting it onto white and black backgrounds and comparing the results.
这篇关于确定GIF在Python中是否透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!