Python练习册--PIL处理图片之加水印

背景

最近在看到了Python 练习册,每天一个小程序 这个项目,非常有趣,也比较实用.

晚上看了这第000题,关于Python图片处理:

将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果

之前没怎么使用过PIL库,在生成验证码及识别验证码时也需要了解这方面知识,就动手试了实践下.


PIL

The Python Imaging Library adds image processing capabilities to your Python interpreter. 这个库提供了广泛的文件格式支持、高效的内部表示以及相当强大的图像处理功能。

文档在这:http://omz-software.com/pythonista/docs/ios/PIL.html

思路

题目的意思实际就是为图片加水印,具体可分以下2步:

  1. 将文本"转"成图片
  2. 将生成的水印图片跟原图相"叠加"

原理差不多就是这样子,具体处理还得使用PIL.


image alt text

最后贴上代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-11-29 19:09:59
# @Author  : Linsir (vi5i0n@hotmail.com)
# @Link    : http://Linsir.sinaapp.com

import Image, ImageEnhance, ImageDraw, ImageFont

def text2img(text, font_color="Blue", font_size=25):
    """生成内容为 TEXT 的水印"""

    font = ImageFont.truetype('simsun.ttc', font_size)
    #多行文字处理
    text = text.split('\n')
    mark_width = 0
    for  i in range(len(text)):
        (width, height) = font.getsize(text[i])
        if mark_width < width:
            mark_width = width
    mark_height = height * len(text)

    #生成水印图片
    mark = Image.new('RGBA', (mark_width,mark_height))
    draw = ImageDraw.ImageDraw(mark, "RGBA")
    draw.setfont(font)
    for i in range(len(text)):
        (width, height) = font.getsize(text[i])
        draw.text((0, i*height), text[i], fill=font_color)
    return mark

def set_opacity(im, 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):
    """添加水印"""

    try:
        if opacity < 1:
            mark = set_opacity(mark, opacity)
        if im.mode != 'RGBA':
            im = im.convert('RGBA')
        if im.size[0] < mark.size[0] or im.size[1] < mark.size[1]:
            print "The mark image size is larger size than original image file."
            return False

        #设置水印位置
        if position == 'left_top':
            x = 0
            y = 0
        elif position == 'left_bottom':
            x = 0
            y = im.size[1] - mark.size[1]
        elif position == 'right_top':
            x = im.size[0] - mark.size[0]
            y = 0
        elif position == 'right_bottom':
            x = im.size[0] - mark.size[0]
            y = im.size[1] - mark.size[1]
        else:
            x = (im.size[0] - mark.size[0]) / 2
            y = (im.size[1] - mark.size[1]) / 2

        layer =Image.new('RGBA', im.size,)
        layer.paste(mark,(x,y))returnImage.composite(layer, im, layer)exceptExceptionas e:print">>>>>>>>>>> WaterMark EXCEPTION:  "+ str(e)returnFalsedef main():
    text = u'Linsir.水印.\nvi5i0n@hotmail.com'# text = open('README.md').read().decode('utf-8')# print text
    im =Image.open('origal.png')
    mark = text2img(text)
    image = watermark(im, mark,'center',0.9)if image:
        image.save('watermark.png')
        image.show()else:print"Sorry, Failed."if __name__ =='__main__':
    main()

其实会了这些代码,也就可以做些像: python生成图片验证码10 行代码判定色图片,PYTHON生成图片,生成长微博之类的事了.

enjoy it .

posted @ 2015-01-17 20:52  CalvinChu  阅读(2067)  评论(0编辑  收藏  举报