annotate photologue/utils/watermark.py @ 179:574cdd0241af

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