Ofe*_*mon 8 python transparency image python-imaging-library
我正在将图像粘贴到另一个图像上,在查看此问题后,我看到为了粘贴透明图像,您需要执行
background = Image.open("test1.png")
foreground = Image.open("test2.png")
background.paste(foreground, (0, 0), foreground)
Run Code Online (Sandbox Code Playgroud)
使用正常图像,您应该这样做
background = Image.open("test1.png")
foreground = Image.open("test2.png")
background.paste(foreground, (0, 0)) // difference here
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何检查图像是否透明,以便确定如何使用该paste方法(有或没有最后一个参数)。
Vin*_*tch 10
我提出了以下函数作为解决方案,它将 PILImage对象作为参数。如果图像使用索引颜色(例如在 GIF 中),它会获取调色板 ( img.info.get("transparency", -1)) 中透明颜色的索引,并检查它是否在画布 ( img.getcolors())中的任何位置使用。如果图像处于 RGBA 模式,那么它可能具有透明度,但它通过获取每个通道 ( img.getextrema())的最小值和最大值进行双重检查,并检查 alpha 通道的最小值是否低于 255。
def has_transparency(img):
if img.mode == "P":
transparent = img.info.get("transparency", -1)
for _, index in img.getcolors():
if index == transparent:
return True
elif img.mode == "RGBA":
extrema = img.getextrema()
if extrema[3][0] < 255:
return True
return False
Run Code Online (Sandbox Code Playgroud)
检查图像的模式以获取 Alpha 透明层。例如,RGB 没有透明度,但 RGBA 具有透明度。
有关更多信息,请参阅https://pillow.readthedocs.io/en/latest/handbook/concepts.html。