美文网首页
github/Show me the code (10)

github/Show me the code (10)

作者: 知识分子中的文盲 | 来源:发表于2016-05-08 23:23 被阅读55次

第 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")

相关文章

网友评论

      本文标题:github/Show me the code (10)

      本文链接:https://www.haomeiwen.com/subject/eszsrttx.html