欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python生成随机验证码(中文验证码)示例

程序员文章站 2023-10-17 20:47:17
复制代码 代码如下:# -*- coding: utf-8 -*-import image,imagedraw,imagefontimport randomimport m...

复制代码 代码如下:

# -*- 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)