|
5
|
1 |
""" Function for applying watermarks to images. |
|
|
2 |
|
|
|
3 |
Original found here: |
|
|
4 |
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879 |
|
|
5 |
|
|
|
6 |
""" |
|
|
7 |
|
|
|
8 |
try: |
|
|
9 |
import Image |
|
|
10 |
import ImageEnhance |
|
|
11 |
except ImportError: |
|
|
12 |
try: |
|
|
13 |
from PIL import Image |
|
|
14 |
from PIL import ImageEnhance |
|
|
15 |
except ImportError: |
|
|
16 |
raise ImportError("The Python Imaging Library was not found.") |
|
|
17 |
|
|
|
18 |
def reduce_opacity(im, opacity): |
|
|
19 |
"""Returns an image with reduced opacity.""" |
|
|
20 |
assert opacity >= 0 and opacity <= 1 |
|
|
21 |
if im.mode != 'RGBA': |
|
|
22 |
im = im.convert('RGBA') |
|
|
23 |
else: |
|
|
24 |
im = im.copy() |
|
|
25 |
alpha = im.split()[3] |
|
|
26 |
alpha = ImageEnhance.Brightness(alpha).enhance(opacity) |
|
|
27 |
im.putalpha(alpha) |
|
|
28 |
return im |
|
|
29 |
|
|
|
30 |
def apply_watermark(im, mark, position, opacity=1): |
|
|
31 |
"""Adds a watermark to an image.""" |
|
|
32 |
if opacity < 1: |
|
|
33 |
mark = reduce_opacity(mark, opacity) |
|
|
34 |
if im.mode != 'RGBA': |
|
|
35 |
im = im.convert('RGBA') |
|
|
36 |
# create a transparent layer the size of the image and draw the |
|
|
37 |
# watermark in that layer. |
|
|
38 |
layer = Image.new('RGBA', im.size, (0,0,0,0)) |
|
|
39 |
if position == 'tile': |
|
|
40 |
for y in range(0, im.size[1], mark.size[1]): |
|
|
41 |
for x in range(0, im.size[0], mark.size[0]): |
|
|
42 |
layer.paste(mark, (x, y)) |
|
|
43 |
elif position == 'scale': |
|
|
44 |
# scale, but preserve the aspect ratio |
|
|
45 |
ratio = min( |
|
|
46 |
float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1]) |
|
|
47 |
w = int(mark.size[0] * ratio) |
|
|
48 |
h = int(mark.size[1] * ratio) |
|
|
49 |
mark = mark.resize((w, h)) |
|
|
50 |
layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2)) |
|
|
51 |
else: |
|
|
52 |
layer.paste(mark, position) |
|
|
53 |
# composite the watermark with the layer |
|
|
54 |
return Image.composite(layer, im, layer) |
|
|
55 |
|
|
|
56 |
def test(): |
|
|
57 |
im = Image.open('test.png') |
|
|
58 |
mark = Image.open('overlay.png') |
|
|
59 |
watermark(im, mark, 'tile', 0.5).show() |
|
|
60 |
watermark(im, mark, 'scale', 1.0).show() |
|
|
61 |
watermark(im, mark, (100, 100), 0.5).show() |
|
|
62 |
|
|
|
63 |
if __name__ == '__main__': |
|
|
64 |
test() |