Source

BlogExample / Python / watermark.py

Full commit
# -*- coding: utf-8 -*-

import os.path
import sys
from PIL import Image, ImageFont, ImageDraw, ImageEnhance, ImageOps

WHITEBORDER = 2
BLACKBORDER = 40

def add_watermark(im, inputtext, font = None, color = None, opacity = .5):
    """
    Aggiunge un watermark alla foto
    """
    if im.mode != "RGBA":
        im = im.convert("RGBA")

    textlayer = Image.new("RGBA", im.size, (0, 0, 0, 0))
    textdraw = ImageDraw.Draw(textlayer)
    textsize = textdraw.textsize(inputtext, font = font)

    for y in range(92, im.size[1], 300):
        for x in range(92, im.size[0], 800):
            textdraw.text((x , y), inputtext, font = font, fill = color)

    if opacity != 1:
        alpha = textlayer.split()[3]
        alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
        textlayer.putalpha(alpha)

    return Image.composite(textlayer, im, textlayer)

def add_frame(im):
    """
    Aggiunge la cornice alla foto
    """

    img = ImageOps.expand(im, border = BLACKBORDER, fill = 'black')
    img = ImageOps.expand(img, border = WHITEBORDER, fill = 'white')
    img = ImageOps.expand(img, border = BLACKBORDER, fill = 'black')

    return img

def file_name_saved(fileroot):
    """
    Modifico il nome del file da salvare
    """

    root, filenamefull = os.path.split(fileroot)
    filename, extension = os.path.splitext(filenamefull)

    return os.path.join(root, filename + '_watermarked' + extension)

def main():
    """
        sys.argv[1] Path del file da modificare
        sys.argv[2] Font da utilizzare 
    """

    if sys.argv > 1:
        try:
            img = Image.open(sys.argv[1])
            font = ImageFont.truetype(sys.argv[2], 80)
        except IOError:
            print "Il File non trovato"
            return

        newimgframe = add_watermark(img, sys.argv[3], font, 'white', 0.3)
        newimgwatermark = add_frame(newimgframe)
        newimgwatermark.save(file_name_saved(sys.argv[1]), "JPEG")

if __name__ == "__main__":
    main()