1

我正在尝试找到一种为 gif 图像加水印的方法,下面是我的代码:

img = Image.open("my.gif")
watermark = Image.open("watermark.gif")

img.paste(watermark, (1, 1))
img.save("out.gif")

文件:我的.gif:

我的.gif

文件:水印.gif:

水印 Gif

输出“out.gif”不再是动画,它显示带有水印的一帧: 出.gif

我知道 PIL 支持 GIF 格式,所以我一定是做错了什么。感谢所有帮助。

4

2 回答 2

4

Animated GIFs are actually a sequence of images with rules and times for switching between them you need to modify all of them and output all of them - you can use images2gif for this - or you can do a lot of work yourself.

Example of using images2gif, after downloading from the above link:

from PIL import Image
import images2gif as i2g
images = i2g.readGif('Animated.gif', False)
watermark = Image.open("Watermark.gif")
for i in images: i.paste(watermark, (1, 1))

i2g.writeGif('Out.gif', images, 0.5) # You may wish to play with the timing, etc.
exit()

And the results: enter image description here

于 2013-08-30T10:46:49.603 回答
2

Images2gif 在 Python 3 上不起作用。我检查了 PIL 文档,它支持读取 GIF 图像,但是保存时,图像不是动画的。我需要为我们应用用户上传的图片添加水印,我已经完成的代码如下。它适用于无 GIF 图像。

def watermark(fp, text, position=None, font=None, quality=85):
    if isinstance(fp, bytes):
        fp = BytesIO(fp)
    im = Image.open(fp)

    water_im = Image.new("RGBA", im.size)
    water_draw = ImageDraw.ImageDraw(water_im)
    if isinstance(font, str):
        font = ImageFont.truetype(font, 10 + int(im.size[0] / 100))
    if not position:
        water_size = water_draw.textsize(text, font=font)
        position = (im.size[0] - water_size[0] * 1.05,
                    im.size[1] - water_size[1] * 1.2)
    water_draw.text(position, text, font=font)
    water_mask = water_im.convert("L").point(lambda x: min(x, 160))
    water_im.putalpha(water_mask)

    if im.format == 'GIF':
        for frame in ImageSequence.Iterator(im):
            frame.paste(water_im, None, water_im)
    else:
        im.paste(water_im, None, water_im)
    out = BytesIO()
    im.save(out, im.format, quality=quality, **im.info)

    return out.getvalue()
于 2014-12-26T07:50:28.777 回答