42

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).

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
gratz
  • 1,506
  • 3
  • 16
  • 34

1 Answers1

65

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')
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • 4
    As long as the 4th value in the `color` parameter (in this example `(255, 0, 0, 0)`) is set to `0`, the image will be completely transparent - this is the value of the alpha channel. All of those should work exactly the same: `(255, 255, 255, 0)`, `(0, 0, 0, 0)`, `(100, 100, 100, 0)` – RealA10N Aug 31 '19 at 13:53
  • 1
    For animated GIFs, I had to use the following code: https://gist.github.com/egocarib/ea022799cca8a102d14c54a22c45efe0 – HCLivess Dec 07 '21 at 04:07