Watermarks with PIL

About

A friend was facing problems regarding some artistic photos being copied from his website without any credits, and was wondering what to do. One of the suggestions was including a diagonal watermark in the high resolution pictures preventing people from easily copying photos without actually contacting him.

I present below a small Python program which uses the Python Imaging Library to build a diagonal textual watermark. It will adapt the generated mark size to the text and image provided.

Sample

Here is a sample of how the watermark looks like:

watermark.jpg

Code

from PIL import Image, ImageDraw, ImageFont
from math import atan, degrees
import sys
import os

FONT = "/usr/X11R6/lib/X11/fonts/TTF/Vera.ttf"

def main(filename, text, outfilename):
    img = Image.open(filename).convert("RGB")
    watermark = Image.new("RGBA", (img.size[0], img.size[1]))
    draw = ImageDraw.ImageDraw(watermark, "RGBA")
    size = 0
    while True:
        size += 1
        nextfont = ImageFont.truetype(FONT, size)
        nexttextwidth, nexttextheight = nextfont.getsize(text)
        if nexttextwidth+nexttextheight/3 > watermark.size[0]:
            break
        font = nextfont
        textwidth, textheight = nexttextwidth, nexttextheight
    draw.setfont(font)
    draw.text(((watermark.size[0]-textwidth)/2,
               (watermark.size[1]-textheight)/2), text)
    watermark = watermark.rotate(degrees(atan(float(img.size[1])/
                                              img.size[0])),
                                 Image.BICUBIC)
    mask = watermark.convert("L").point(lambda x: min(x, 55))
    watermark.putalpha(mask)
    img.paste(watermark, None, watermark)
    img.save(outfilename)

if __name__ == "__main__":
    if len(sys.argv) != 4:
        sys.exit("Usage: %s <input-image> <text> <output-image>"
                 % os.path.basename(sys.argv[0]))
    main(*sys.argv[1:])


CategorySnippet

snippets/watermarks (last edited 2008-03-03 03:31:09 by GustavoNiemeyer)