How to CREATE a transparent gif (or png) with PIL (python-imaging)

gratz picture gratz · Dec 4, 2011 · Viewed 42.1k times · Source

Trying to create a transparent gif with PIL. So far I have this:

    from PIL import Image

    img = Image.new('RGBA', (100, 100), (255, 0, 0, 0))
    img.save("test.gif", "GIF", transparency=0)

Everything I've found so far refers to manipulating an existing image to adjust it's transparency settings or overlaying a transparent image onto another. I merely want to create a transparent GIF (to then draw onto).

Answer

ekhumoro picture ekhumoro · Dec 4, 2011

The following script creates a transparent GIF with a red circle drawn in the middle:

from PIL import Image, ImageDraw

img = Image.new('RGBA', (100, 100), (255, 0, 0, 0))

draw = ImageDraw.Draw(img)
draw.ellipse((25, 25, 75, 75), fill=(255, 0, 0))

img.save('test.gif', 'GIF', transparency=0)

and for PNG format:

img.save('test.png', 'PNG')