Convert non-transparent image to transparent gif image PIL

大兔子大兔子 提交于 2020-06-27 18:38:09

问题


Is it possible to 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.

Thanks!


回答1:


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.




回答2:


Just now I was able to convert a non-transparent PNG file to a GIF with a transparent background using the web site: onlinepngtools.com



来源:https://stackoverflow.com/questions/61925648/convert-non-transparent-image-to-transparent-gif-image-pil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!