It's not obvious, to me at least, how you are supposed to do that! This may be an unnecessary work-around for a problem that doesn't exist because I don't know something about how PIL works internally.
Anyway, I messed around with it long enough using this input image:
#!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageOps
# Open PNG image and ensure no alpha channel
im = Image.open('start.png').convert('RGB')
# Draw alpha layer - black square with white circle
alpha = Image.new('L', (100,100), 0)
ImageDraw.Draw(alpha).ellipse((10,10,90,90), fill=255)
# Add our lovely new alpha layer to image
im.putalpha(alpha)
# Save result as PNG and GIF
im.save('result.png')
im.save('unhappy.gif')
When I get to here, the PNG works and the GIF is "unhappy".
PNG below:
"Unhappy" GIF below:
Here is how I fixed up the GIF:
# Extract the alpha channel
alpha = im.split()[3]
# Palettize original image leaving last colour free for transparency index
im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
# Put 255 everywhere in image where we want transparency
im.paste(255, ImageOps.invert(alpha))
im.save('result.gif', transparency=255)
Keywords: Python, image processing, PIL, Pillow, GIF, transparency, alpha, preserve, transparent index.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…