第三方库PIL简单使用

PIL为第三方库,需要简单安装,最容易的安装方法 pip install PIL 

详细内容见http://effbot.org/imagingbook/

下面展示一个简单用例:(字母验证码简单实现)

#-*-coding:utf-8-*-
#author:wangxing

from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random

#chinese = '去我额人他有哦怕了看就和个发的是啊'
#lich = list(chinese)
#res = random.sample(lich,4)
#print res
#尝试显示中文验证码,ascii码没有中文标识。可以自己制定中文字符范围,并从中获取随机字符。

#随机字母
def randnum():
return chr(random.randint(65,90))

#随机颜色1
def randColor1():
return (random.randint(64,255),random.randint(64,255),random.randint(64,255))

def randColor2():
return (random.randint(32,127),random.randint(32,127),random.randint(32,127))

width = 240
height = 60
image = Image.new('RGB',(width,height),(255,255,255))

font = ImageFont.truetype('C:\Windows\Fonts\Arial.ttf',36)

draw = ImageDraw.Draw(image)

for x in range(width):
for y in range(height):
draw.point((x,y),fill=randColor1())

for t in range(4):
draw.text((60*t+10,10),randnum(),font=font,fill=randColor2())


#draw.text(res,font=font,fill=randColor2())
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg','jpeg')
posted @ 2017-11-14 19:21  菜鸟的日记  阅读(532)  评论(0编辑  收藏  举报