def reduce_opacity(im, opacity):
"""Returns an image with reduced opacity."""
assert 0 <= opacity <= 1
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)
return im
def watermark(im, mark, position=None, opacity=1, angle=45, density=(100, 100), resize=None, min_size=None):
if opacity < 1:
mark = reduce_opacity(mark, opacity)
if im.mode != 'RGBA':
im = im.convert('RGBA')
if resize:
im.thumbnail(resize, Image.ANTIALIAS)
layer = Image.new('RGBA', (im.size[0], im.size[1]), (0, 0, 0, 0))
if min_size is None or (im.size[0] > min_size[0] or im.size[1] > min_size[1]):
if position:
if position == 'tile':
mark = mark.rotate(angle, expand=True)
for y in range(0, layer.size[1], mark.size[1]+density[1]):
for x in range(0, layer.size[0], mark.size[0]+density[0]):
layer.paste(mark, (x, y))
elif position == 'scale':
# scale, but preserve the aspect ratio
ratio = min(
float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
w = int(mark.size[0] * ratio)
h = int(mark.size[1] * ratio)
mark = mark.resize((w, h))
layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
elif position == 'center':
y = (im.size[1] - mark.size[1]) / 2
x = (im.size[0] - mark.size[0]) / 2
layer.paste(mark, (x, y))
elif position == 'upper-left':
x = 0
y = 0
layer.paste(mark, (x, y))
elif position == 'lower-left':
x = 0
y = im.size[1] - mark.size[1]
layer.paste(mark, (x, y))
elif position == 'upper-right':
x = im.size[0] - mark.size[0]
y = 0
layer.paste(mark, (x, y))
elif position == 'lower-right':
x = im.size[0] - mark.size[0]
y = im.size[1] - mark.size[1]
layer.paste(mark, (x, y))
elif position == 'corners':
x = 0
y = 0
layer.paste(mark, (x, y))
x = 0
y = im.size[1] - mark.size[1]
layer.paste(mark, (x, y))
x = im.size[0] - mark.size[0]
y = 0
layer.paste(mark, (x, y))
x = im.size[0] - mark.size[0]
y = im.size[1] - mark.size[1]
layer.paste(mark, (x, y))
elif position == 'none':
pass
else:
layer.paste(mark, position)
# composite the watermark with the layer
im = Image.composite(layer, im, layer)
return im
мой вариант