python使用PIL模块实现给图片打水印的方法

yipeiwu_com6年前Python基础

本文实例讲述了python使用PIL模块实现给图片打水印的方法。分享给大家供大家参考。具体实现方法如下:

import Image, ImageEnhance
def reduce_opacity(im, opacity):
  """Returns an image with reduced opacity."""
  assert opacity >= 0 and 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, opacity=1):
  """Adds a watermark to an image."""
  if opacity < 1:
    mark = reduce_opacity(mark, opacity)
  if im.mode != 'RGBA':
    im = im.convert('RGBA')
  # create a transparent layer the size of the image and draw the
  # watermark in that layer.
  layer = Image.new('RGBA', im.size, (0,0,0,0))
  if position == 'tile':
    for y in range(0, im.size[1], mark.size[1]):
      for x in range(0, im.size[0], mark.size[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))
  else:
    layer.paste(mark, position)
  # composite the watermark with the layer
  return Image.composite(layer, im, layer)
def test():
  im = Image.open('test.png')
  mark = Image.open('overlay.png')
  watermark(im, mark, 'tile', 0.5).show()
  watermark(im, mark, 'scale', 1.0).show()
  watermark(im, mark, (100, 100), 0.5).show()
if __name__ == '__main__':
  test()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python处理XML格式数据的方法详解

本文实例讲述了Python处理XML格式数据的方法。分享给大家供大家参考,具体如下: 这里的操作是基于Python3平台。 在使用Python处理XML的问题上,首先遇到的是编码问题。...

Python中字典和集合学习小结

映射类型:     表示一个任意对象的集合,且可以通过另一个几乎是任意键值的集合进行索引     与序列不同,映射是无序的,通...

python中dir()与__dict__属性的区别浅析

前言 只要是有属性的数据对象(不一定是面向对象的对象实例,而是指具有数据类型的数据对象),都可以通过__dict__和dir()来显示数据对象的相关属性。 __dict__可以看作...

使用Python编写一个模仿CPU工作的程序

今天早上早些时候,在我的Planet Python源中,我读到了一篇有趣的文章"开发CARDIAC:纸板计算机(Developing upwards: CARDIAC: The Card...

python版DDOS攻击脚本

本文实例为大家分享了python版DDOS攻击脚本,供大家参考,具体内容如下 于是就找到了我之前收藏的一篇python的文章,是关于ddos攻击的一个脚本,正好今天有空,就实践下了。 附...