bgneal@1: """ Function for applying watermarks to images.
bgneal@1: 
bgneal@1: Original found here:
bgneal@1: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
bgneal@1: 
bgneal@1: """
bgneal@1: 
bgneal@1: try:
bgneal@1:     import Image
bgneal@1:     import ImageEnhance
bgneal@1: except ImportError:
bgneal@1:     try:
bgneal@1:         from PIL import Image
bgneal@1:         from PIL import ImageEnhance
bgneal@1:     except ImportError:
bgneal@1:         raise ImportError("The Python Imaging Library was not found.")
bgneal@1: 
bgneal@1: def reduce_opacity(im, opacity):
bgneal@1:     """Returns an image with reduced opacity."""
bgneal@1:     assert opacity >= 0 and opacity <= 1
bgneal@1:     if im.mode != 'RGBA':
bgneal@1:         im = im.convert('RGBA')
bgneal@1:     else:
bgneal@1:         im = im.copy()
bgneal@1:     alpha = im.split()[3]
bgneal@1:     alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
bgneal@1:     im.putalpha(alpha)
bgneal@1:     return im
bgneal@1: 
bgneal@1: def apply_watermark(im, mark, position, opacity=1):
bgneal@1:     """Adds a watermark to an image."""
bgneal@1:     if opacity < 1:
bgneal@1:         mark = reduce_opacity(mark, opacity)
bgneal@1:     if im.mode != 'RGBA':
bgneal@1:         im = im.convert('RGBA')
bgneal@1:     # create a transparent layer the size of the image and draw the
bgneal@1:     # watermark in that layer.
bgneal@1:     layer = Image.new('RGBA', im.size, (0,0,0,0))
bgneal@1:     if position == 'tile':
bgneal@1:         for y in range(0, im.size[1], mark.size[1]):
bgneal@1:             for x in range(0, im.size[0], mark.size[0]):
bgneal@1:                 layer.paste(mark, (x, y))
bgneal@1:     elif position == 'scale':
bgneal@1:         # scale, but preserve the aspect ratio
bgneal@1:         ratio = min(
bgneal@1:             float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
bgneal@1:         w = int(mark.size[0] * ratio)
bgneal@1:         h = int(mark.size[1] * ratio)
bgneal@1:         mark = mark.resize((w, h))
bgneal@1:         layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
bgneal@1:     else:
bgneal@1:         layer.paste(mark, position)
bgneal@1:     # composite the watermark with the layer
bgneal@1:     return Image.composite(layer, im, layer)
bgneal@1: 
bgneal@1: def test():
bgneal@1:     im = Image.open('test.png')
bgneal@1:     mark = Image.open('overlay.png')
bgneal@1:     watermark(im, mark, 'tile', 0.5).show()
bgneal@1:     watermark(im, mark, 'scale', 1.0).show()
bgneal@1:     watermark(im, mark, (100, 100), 0.5).show()
bgneal@1: 
bgneal@1: if __name__ == '__main__':
bgneal@1:     test()