MCPcopy Create free account
hub / github.com/ActiveState/code / watermark

Function watermark

recipes/Python/362879_Watermark_with_PIL/recipe-362879.py:15–39  ·  view source on GitHub ↗

Adds a watermark to an image.

(im, mark, position, opacity=1)

Source from the content-addressed store, hash-verified

13 return im
14
15def watermark(im, mark, position, opacity=1):
16 """Adds a watermark to an image."""
17 if opacity < 1:
18 mark = reduce_opacity(mark, opacity)
19 if im.mode != 'RGBA':
20 im = im.convert('RGBA')
21 # create a transparent layer the size of the image and draw the
22 # watermark in that layer.
23 layer = Image.new('RGBA', im.size, (0,0,0,0))
24 if position == 'tile':
25 for y in range(0, im.size[1], mark.size[1]):
26 for x in range(0, im.size[0], mark.size[0]):
27 layer.paste(mark, (x, y))
28 elif position == 'scale':
29 # scale, but preserve the aspect ratio
30 ratio = min(
31 float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
32 w = int(mark.size[0] * ratio)
33 h = int(mark.size[1] * ratio)
34 mark = mark.resize((w, h))
35 layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
36 else:
37 layer.paste(mark, position)
38 # composite the watermark with the layer
39 return Image.composite(layer, im, layer)
40
41def test():
42 im = Image.open('test.png')

Callers 1

testFunction · 0.85

Calls 7

reduce_opacityFunction · 0.85
rangeFunction · 0.85
minFunction · 0.85
convertMethod · 0.45
newMethod · 0.45
pasteMethod · 0.45
resizeMethod · 0.45

Tested by

no test coverage detected