python第七题 生成随机验证码


from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from pylab import *
import random,numpy,string

path = "G:\python文件"

text = random.sample(string.ascii_letters,4)
#random.sample是可以从指定的序列中,随机的截取指定长度的片断
#string.letters是生成英文字母
print(text)

# generate 3-D random array 三维的
rawArray = numpy.zeros((100,300,3),dtype=numpy.uint8) #uint8无符号8位整型
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)): #4次
draw.text((75*i+random.randint(0,40),random.randint(0,40)), text[i],
font=ImageFont.truetype("STXINGKA.TTF",80),
fill = (random.randint(0,255),random.randint(0,255),random.randint(0,255)))
#第一个参数指定绘制的起始点(文本的左上角所在位置),第二个参数指定文本内容,第三个参数指定文本的颜色,
# 第四个参数指定字体(通过ImageFont类来定义)
im.save(path+"/checkcode.jpg")

总结:其实,代码中有一部分我是没有弄明白的,就是关于数组那,我还没有深入的了解,只是大体的查了查每个参数的意义。这里又用到了PIL 就是关于图像的绘制,可见,这也是个重要的地方,需要掌握。
posted @ 2018-02-01 21:46  BUSYGIRL  阅读(193)  评论(0编辑  收藏  举报