【问题标题】:Convert non-transparent image to transparent GIF image PIL将非透明图像转换为透明 GIF 图像 PIL
【发布时间】:2021-03-15 06:41:00
【问题描述】:

如何使用 PIL 将不透明的 PNG 文件转换为透明的 GIF 文件?

我的海龟图形游戏需要它。我似乎只能透明化 PNG 文件,而不是 GIF 文件。

【问题讨论】:

    标签: python image python-imaging-library transparency


    【解决方案1】:

    至少对我来说,你应该如何做到这一点并不明显!对于不存在的问题,这可能是不必要的解决方法,因为我不知道 PIL 内部如何工作。

    不管怎样,我用这个输入图像搞砸了足够长的时间:

    #!/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')
    

    当我到达这里时,PNG 工作正常,而 GIF 是 “不开心”

    下面的PNG:

    “不开心”下面的 GIF:

    这是我修复 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)
    

    关键字:Python、图像处理、PIL、Pillow、GIF、透明度、alpha、preserve、透明索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      相关资源
      最近更新 更多