[Python] python利用PIL给图片打水印水印 →→→→→进入此内容的聊天室

来自 , 2019-09-06, 写在 Python, 查看 109 次.
URL http://www.code666.cn/view/aa0d2a80
  1. import Image, ImageEnhance
  2.  
  3. def reduce_opacity(im, opacity):
  4.     """Returns an image with reduced opacity."""
  5.     assert opacity >= 0 and opacity <= 1
  6.     if im.mode != 'RGBA':
  7.         im = im.convert('RGBA')
  8.     else:
  9.         im = im.copy()
  10.     alpha = im.split()[3]
  11.     alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
  12.     im.putalpha(alpha)
  13.     return im
  14.  
  15. def 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.  
  41. def test():
  42.     im = Image.open('test.png')
  43.     mark = Image.open('overlay.png')
  44.     watermark(im, mark, 'tile', 0.5).show()
  45.     watermark(im, mark, 'scale', 1.0).show()
  46.     watermark(im, mark, (100, 100), 0.5).show()
  47.  
  48. if __name__ == '__main__':
  49.     test()
  50. #//python/6120

回复 "python利用PIL给图片打水印水印"

这儿你可以回复上面这条便签

captcha