factorisation
[Portfolio.git] / Extensions / watermark.py
1 # -*- coding: utf-8 -*-
2 ############################################################
3 # Copyright © 2005-2008 Benoît PIN <benoit.pin@ensmp.fr> #
4 # Plinn - http://plinn.org #
5 # #
6 # This program is free software; you can redistribute it #
7 # and/or modify it under the terms of the Creative Commons #
8 # "Attribution-Noncommercial 2.0 Generic" #
9 # http://creativecommons.org/licenses/by-nc/2.0/ #
10 ############################################################
11 """
12
13
14 """
15
16 from Globals import package_home
17 from os import path
18 from PIL.Image import open as imgopen
19 from ImageDraw import Draw
20 from PIL.ImageDraw import Draw
21 from PIL.ImageFont import truetype
22 from Products.Portfolio.Extensions import fontdir
23 from Products.Photo.cache import memoizedmethod
24
25 class FontCache:
26 def __init__(self) :
27 self._methodResultsCache = {}
28
29 @memoizedmethod('name', 'size', 'index')
30 def get(self, name, size, index) :
31 fontfile = path.join(fontdir, name)
32 font = truetype(fontfile, size, index=index)
33 return font
34
35
36 fontCache = FontCache()
37
38
39 def addWatermark(self, image, text, size=20, margin_right=10, margin_bottom=10, font='verdana.ttf', index=0, encoding='utf-8') :
40
41 font = fontCache.get(font, size, index)
42 text = text.decode(encoding)
43 tw, th = font.getsize(text)
44 iw, ih = image.size
45
46 d = Draw(image)
47
48 left, top = (iw - tw - margin_right, ih - th - margin_bottom)
49
50 d.text((left, top), text, font = font)