Python 随机生成中文验证码的实例代码

yipeiwu_com5年前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")

相关文章

Python Queue模块详细介绍及实例

Python Queue模块 Python中,队列是线程间最常用的交换数据的形式。Queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外。 创建一个“队列...

Python小程序之在图片上加入数字的代码

Python小程序之在图片上加入数字的代码

在GitHub上发现一些很有意思的项目,由于本人作为Python的初学者,编程代码能力相对薄弱,为了加强Python的学习,特此利用前辈们的学习知识成果,自己去亲自实现。 来源:Gi...

Python使用matplotlib 画矩形的三种方式分析

Python使用matplotlib 画矩形的三种方式分析

本文实例讲述了Python使用matplotlib 画矩形的三种方式。分享给大家供大家参考,具体如下: 假设矩形两点坐标如下,分别为:x1, y1, x2, y2 cat_dict[...

python中对list去重的多种方法

今天遇到一个问题,在同事随意的提示下,用了 itertools.groupby 这个函数。不过这个东西最终还是没用上。 问题就是对一个list中的新闻id进行去重,去重之后要保证顺序不变...

利用python实现在微信群刷屏的方法

利用python实现在微信群刷屏的方法

hello,我是小小炽,这是我写的第一篇博客,写博客一直都想在写,但是苦于能力尚浅,在各位大牛面前那既然是关公面前耍大刀了,但是其实想来每一个大牛不也是从一个小白慢慢进步学习从而达到一定...