Python 随机生成中文验证码

1. [代码]python代码     跳至 [1] [2] [全屏预览]

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(0x4E000x9FBF)
11     return unichr(val) 
12  
13   @staticmethod
14   def GB2312():
15     head = random.randint(0xB00xCF)
16     body = random.randint(0xA0xF)
17     tail = random.randint(00xF)
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 = (000),
24                      size = (10040),
25                      fontPath = 'wqy.ttc',
26                      bgColor = (255255255),
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(030), 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(0255),
46            random.randint(0255),
47            random.randint(0255)) 
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 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 in range(0, num):
63       char = RandomChar().GB2312()
64       = start + self.fontSize * + random.randint(0, gap) + gap * i
65       self.drawText((x, random.randint(-55)), RandomChar().GB2312(), self.randRGB())
66       self.rotate()
67     self.randLine(18
68  
69   def save(self, path):
70     self.image.save(path)

2. [代码]调用方法     

1 ic = ImageChar(fontColor=(100,21190))
2 ic.randChinese(4)
3 ic.save("1.jpeg")

3. [图片] 效果图    

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值