Python 随机生成中文验证码
http://www.oschina.net/code/snippet_12_325
[代码] python代码
01 |
# -*- coding: utf-8 -*- |
02 |
import Image,ImageDraw,ImageFont |
03 |
import random |
04 |
import math, string |
05 |
06 |
class RandomChar(): |
07 |
"""用于随机生成汉字""" |
08 |
@staticmethod |
09 |
def Unicode(): |
10 |
val = random.randint(0x4E00, 0x9FBF) |
11 |
return unichr(val) |
12 |
13 |
@staticmethod |
14 |
def GB2312(): |
15 |
head = random.randint(0xB0, 0xCF) |
16 |
body = random.randint(0xA, 0xF) |
17 |
tail = random.randint(0, 0xF) |
18 |
val = ( head << 8 ) | (body << 4) | tail |
19 |
str = "%x" % val |
20 |
return str.decode('hex').decode('gb2312') |
21 |
22 |
class ImageChar(): |
23 |
def __init__(self, fontColor = (0, 0, 0), |
24 |
size = (100, 40), |
25 |
fontPath = 'wqy.ttc', |
26 |
bgColor = (255, 255, 255), |
27 |
fontSize = 20): |
28 |
self.size = size |
29 |
self.fontPath = fontPath |
30 |
self.bgColor = bgColor |
31 |
self.fontSize = fontSize |
32 |
self.fontColor = fontColor |
33 |
self.font = ImageFont.truetype(self.fontPath, self.fontSize) |
34 |
self.image = Image.new('RGB', size, bgColor) |
35 |
36 |
def rotate(self): |
37 |
self.image.rotate(random.randint(0, 30), expand=0) |
38 |
39 |
def drawText(self, pos, txt, fill): |
40 |
draw = ImageDraw.Draw(self.image) |
41 |
draw.text(pos, txt, font=self.font, fill=fill) |
42 |
del draw |
43 |
44 |
def randRGB(self): |
45 |
return (random.randint(0, 255), |
46 |
random.randint(0, 255), |
47 |
random.randint(0, 255)) |
48 |
49 |
def randPoint(self): |
50 |
(width, height) = self.size |
51 |
return (random.randint(0, width), random.randint(0, height)) |
52 |
53 |
def randLine(self, num): |
54 |
draw = ImageDraw.Draw(self.image) |
55 |
for i in range(0, num): |
56 |
draw.line([self.randPoint(), self.randPoint()], self.randRGB()) |
57 |
del draw |
58 |
59 |
def randChinese(self, num): |
60 |
gap = 5 |
61 |
start = 0 |
62 |
for i in range(0, num): |
63 |
char = RandomChar().GB2312() |
64 |
x = start + self.fontSize * i + random.randint(0, gap) + gap * i |
65 |
self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB()) |
66 |
self.rotate() |
67 |
self.randLine(18) |
68 |
69 |
def save(self, path): |
70 |
self.image.save(path) |
[代码] 调用方法
1 |
ic = ImageChar(fontColor=(100,211, 90)) |
2 |
ic.randChinese(4) |
3 |
ic.save("1.jpeg") |
[图片] 效果图

浙公网安备 33010602011771号