Daniel
Daniel

Reputation: 3077

Watermark GIF with Python PIL

I'm trying to find a way to watermark a gif image, below is my code:

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

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

File: my.gif:

my.gif

File: watermark.gif:

Watermark Gif

the output "out.gif" is no longer animated, it shows one frame with the watermark: Out.gif

I know that PIL supports the GIF format, so I must be doing something wrong. All help is appreciated.

Upvotes: 1

Views: 2826

Answers (2)

Jagger Wang
Jagger Wang

Reputation: 21

Images2gif not working on Python 3. I checked PIL doc, it support reading GIF image, but when saved, the image is not animated. I have a requirement to watermark images uploaded by our app's user, the code I've already done as following. It worked for none GIF images.

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

Upvotes: 2

Steve Barnes
Steve Barnes

Reputation: 28405

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

Upvotes: 4

Related Questions