Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...