拍爱

watermark_utils.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # -*- coding: utf-8 -*-
  2. try:
  3. import Image
  4. import ImageEnhance
  5. except ImportError:
  6. from PIL import Image, ImageEnhance
  7. def reduce_opacity(im, opacity):
  8. """Returns an image with reduced opacity."""
  9. assert 0 <= opacity <= 1
  10. im = im.convert('RGBA') if im.mode != 'RGBA' else im.copy()
  11. alpha = im.split()[3]
  12. alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
  13. im.putalpha(alpha)
  14. return im
  15. def watermark(im, mark, position, opacity=1, maxsize=(0, 0), possize=(0, 0)):
  16. """ Add watermark to image """
  17. if opacity < 1:
  18. mark = reduce_opacity(mark, opacity)
  19. if im.mode != 'RGBA':
  20. im = im.convert('RGBA')
  21. # Resize mark
  22. w, h = int(min(mark.size[0], maxsize[0]) if maxsize[0] else mark.size[0]), int(min(mark.size[1], maxsize[1]) if maxsize[1] else mark.size[1])
  23. mark = mark.resize((w, h))
  24. # Create a transparent layer the size of the image
  25. # Draw the watermark in that layer.
  26. layer = Image.new('RGBA', im.size, (0, 0, 0, 0))
  27. if position == 'tile':
  28. for y in range(0, im.size[1], mark.size[1]):
  29. for x in range(0, im.size[0], mark.size[0]):
  30. layer.paste(mark, (x, y))
  31. elif position == 'scale':
  32. # Scale, but preserve the aspect ratio
  33. ratio = min(float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
  34. w, h = int(mark.size[0] * ratio), int(mark.size[1] * ratio)
  35. w, h = int(min(w, maxsize[0]) if maxsize[0] else w), int(min(h, maxsize[1]) if maxsize[1] else h)
  36. mark = mark.resize((w, h))
  37. layer.paste(mark, ((im.size[0] - possize[0] or w) / 2, (im.size[1] - possize[1] or h) / 2))
  38. else:
  39. layer.paste(mark, position)
  40. # Composite the watermark with the layer
  41. return Image.composite(layer, im, layer)
  42. def watermark_wrap(im_path, mark_path, save_path=''):
  43. im, mark = Image.open(im_path), Image.open(mark_path)
  44. # new_im = watermark(im, mark, (50, 50), 0.5)
  45. new_im = watermark(im, mark, position='scale', opacity=1.0, maxsize=(400, 505.2), possize=(400, 400))
  46. new_im.save(save_path or im_path)
  47. def watermark_test():
  48. im, mark = Image.open('original_CGzC_10a50000c8811190.jpg'), Image.open('paiai_water_mark.png')
  49. watermark(im, mark, position='tile', opacity=0.5, maxsize=(40, 49.4375)).show()
  50. watermark(im, mark, position='scale', opacity=1.0, maxsize=(400, 494.375), possize=(400, 400)).show()
  51. watermark(im, mark, position=(50, 50), opacity=0.5, maxsize=(40, 49.4375)).show()
  52. if __name__ == '__main__':
  53. # watermark_test()
  54. watermark_wrap('original_CGzC_10a50000c8811190.jpg', 'paiai_water_mark.png')