Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

python - Convert non-transparent image to transparent GIF image PIL

How can I convert a non-transparent PNG file into a transparent GIF file with PIL?

I need it for my turtle-graphics game. I can only seem to transparentize a PNG file, not a GIF file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here

#!/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:

enter image description here

"Unhappy" GIF below:

enter image description here

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)

enter image description here

Keywords: Python, image processing, PIL, Pillow, GIF, transparency, alpha, preserve, transparent index.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...