Python 随机生成中文验证码的实例代码
python代码
# -*- coding: utf-8 -*-
import image,imagedraw,imagefont
import random
import math, string
class randomchar():
"""用于随机生成汉字"""
@staticmethod
def unicode():
val = random.randint(0x4e00, 0x9fbf)
return unichr(val)
@staticmethod
def gb2312():
head = random.randint(0xb0, 0xcf)
body = random.randint(0xa, 0xf)
tail = random.randint(0, 0xf)
val = ( head << 8 ) | (body << 4) | tail
str = "%x" % val
return str.decode('hex').decode('gb2312')
class imagechar():
def __init__(self, fontcolor = (0, 0, 0),
size = (100, 40),
fontpath = 'wqy.ttc',
bgcolor = (255, 255, 255),
fontsize = 20):
self.size = size
self.fontpath = fontpath
self.bgcolor = bgcolor
self.fontsize = fontsize
self.fontcolor = fontcolor
self.font = imagefont.truetype(self.fontpath, self.fontsize)
self.image = image.new('rgb', size, bgcolor)
def rotate(self):
self.image.rotate(random.randint(0, 30), expand=0)
def drawtext(self, pos, txt, fill):
draw = imagedraw.draw(self.image)
draw.text(pos, txt, font=self.font, fill=fill)
del draw
def randrgb(self):
return (random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255))
def randpoint(self):
(width, height) = self.size
return (random.randint(0, width), random.randint(0, height))
def randline(self, num):
draw = imagedraw.draw(self.image)
for i in range(0, num):
draw.line([self.randpoint(), self.randpoint()], self.randrgb())
del draw
def randchinese(self, num):
gap = 5
start = 0
for i in range(0, num):
char = randomchar().gb2312()
x = start + self.fontsize * i + random.randint(0, gap) + gap * i
self.drawtext((x, random.randint(-5, 5)), randomchar().gb2312(), self.randrgb())
self.rotate()
self.randline(18)
def save(self, path):
self.image.save(path)
调用方法
ic = imagechar(fontcolor=(100,211, 90))
ic.randchinese(4)
ic.save("1.jpeg")