PIL
The Python Imaging Library adds image processing capabilities to your Python interpreter. 这个库提供了广泛的文件格式支持、高效的内部表示以及相当强大的图像处理功能。
文档在这:http://omz-software.com/pythonista/docs/ios/PIL.html
思路
题目的意思实际就是为图片加水印,具体可分以下2步:
将文本"转"成图片
将生成的水印图片跟原图相"叠加"
原理差不多就是这样子,具体处理还得使用PIL.
最后贴上代码:
#!/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)
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)
draw.text((0, i*height), text, 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 .