Search code examples
pythonimagepython-imaging-librarytransparency

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.


Solution

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