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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

Django实现全文检索的方法(支持中文)

PS: 我的检索是在文章模块下 forum/article 第一步:先安装需要的包: pip install django-haystack pip install whoosh p...

在Python中使用filter去除列表中值为假及空字符串的例子

在 Python中,认为以下值为假: None # None值 False # False值 0 # 数值零不管它是int,float还是complex类型 '',(),[] #...

python通过百度地图API获取某地址的经纬度详解

python通过百度地图API获取某地址的经纬度详解

前言 这几天比较空闲,就接触了下百度地图的API(开发者中心链接地址:http://developer.baidu.com/),发现调用还是挺方便的,本文将给大家详细的介绍关于pytho...

关于numpy中np.nonzero()函数用法的详解

np.nonzero函数是numpy中用于得到数组array中非零元素的位置(数组索引)的函数。一般来说,通过help(np.nonzero)能够查看到该函数的解析与例程。但是,由于例程...

Python 绘制酷炫的三维图步骤详解

Python 绘制酷炫的三维图步骤详解

通常我们用 Python 绘制的都是二维平面图,但有时也需要绘制三维场景图,比如像下面这样的: 这些图怎么做出来呢?今天就来分享下如何一步步绘制出三维矢量(SVG)图。 八面体 我们先...