在 PIL 中保存 GIF 时透明度不一致

2024-03-25

我正在编写可以覆盖图像并使背景透明的脚本。输出应该是 GIF 格式。

该脚本有效,但对于某些图像,透明度未按预期工作。

这是脚本

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

CANVAS_HEIGHT = 354
CANVAS_WIDTH = 344


def get_text_mask():
    font_style_path = 'Ultra-Regular.ttf'

    text_mask_base = Image.new('L', (CANVAS_WIDTH, CANVAS_HEIGHT), 255)
    text_mask = text_mask_base.copy()
    text_mask_draw = ImageDraw.Draw(text_mask)
    font = ImageFont.truetype(font_style_path, 94)
    text_mask_width, text_mask_height = text_mask_draw.multiline_textsize("1000\nUsers",
                                                                          font=font)

    text_mask_draw.multiline_text(((CANVAS_WIDTH - text_mask_width) / 2,
                                   (CANVAS_HEIGHT - text_mask_height) / 2),
                                  "1000\nUsers",
                                  font=font,
                                  fill=0,
                                  align='center')

    return text_mask


def run():
    images = ['image1.png', 'image2.png']
    for index, original_image in enumerate(images):
        image = Image.open(original_image)
        blank_canvas = Image.new('RGBA', (CANVAS_WIDTH, CANVAS_HEIGHT), (255, 255, 255, 0))
        text_mask = get_text_mask()
        final_canvas = blank_canvas.copy()
        for i in xrange(0, CANVAS_WIDTH, image.width):
            for j in xrange(0, CANVAS_HEIGHT, image.height):
                final_canvas.paste(image, (i, j))

        final_canvas.paste(text_mask, mask=text_mask)
        final_canvas.convert('P', palette=Image.ADAPTIVE)
        final_canvas.save("output-{}.gif".format(index), format="GIF", transparency=0)

run()

enter image description here image1.png

enter image description here image2.png

字体在这里https://bipuljain.com/static/images/Ultra-Regular.ttf https://bipuljain.com/static/images/Ultra-Regular.ttf

And the output with issue. enter image description here

And output working fine. enter image description here


问题是你的“原始图像”包含与 GIF 用来表示“该像素是透明的”相同的索引颜色。

GIF 是“基于调色板的”——该调色板的一个索引被指定为“这是透明的”(参见 f.e.https://en.wikipedia.org/wiki/GIF https://en.wikipedia.org/wiki/GIF)

所以如果你指定pure black or pure white由于颜色索引是透明的,并且您的源图像已经包含具有该确切颜色的像素,因此它们也将是透明的。

为了避免这种情况,您可以对源背景图像进行采样并选择“不存在”的颜色作为透明度颜色 - 这永远不会出现在您的结果图像中。

您还可以更改源图像像素值 - 检查所有像素并稍微更改所有“背景像素”,这样它们就不会变得半透明。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 PIL 中保存 GIF 时透明度不一致 的相关文章

随机推荐