第 0010 题:使用 Python 生成类似于下图中的字母验证码图片
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
#from pylab import *
import random,numpy,string
path = "/home/hqi/source_code/python/show_me_the_code"
# generate 4 ramdom letters
text = random.sample(string.letters, 4)
#print text
# generate 3-D random array
rawArray = numpy.zeros((100, 300, 3), \
dtype=numpy.uint8)
sh = rawArray.shape
for i in range(sh[0]):
for j in range(sh[1]):
for k in range(sh[2]):
rawArray[i][j][k] = random.randint(0,255)
# generate the background pic from 3-D array
im = Image.fromarray(rawArray)
draw = ImageDraw.Draw(im)
# add check code onto the background
for i in range(len(text)):
draw.text((75*i+random.randint(0,40),random.randint(0,40)), text[i],
font=ImageFont.truetype("/usr/share/fonts/truetype/./ubuntu-font-family/Ubuntu-R.ttf",60),
fill = (random.randint(0,255),random.randint(0,255),random.randint(0,255)))
im.save(path+"/veri_code.jpg")