思路

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

  1. 将文本"转"成图片

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

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


p_w_picpath 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.comimport Image, ImageEnhance, ImageDraw, ImageFontdef 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 markdef 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 imdef 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 p_w_picpath size is larger size than original p_w_picpath 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)    p_w_picpath = watermark(im, mark,'center',0.9)if p_w_picpath:        p_w_picpath.save('watermark.png')        p_w_picpath.show()else:print"Sorry, Failed."if __name__ =='__main__':    main()

其实会了这些代码,也就可以做些像: , ,,生成长微博之类的事了.