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

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

相关文章

跟老齐学Python之开始真正编程

跟老齐学Python之开始真正编程

通过对四则运算的学习,已经初步接触了Python中内容,如果看官是零基础的学习者,可能有点迷惑了。难道在IDE里面敲几个命令,然后看到结果,就算编程了?这也不是那些能够自动运行的程序呀?...

使用pyinstaller打包PyQt4程序遇到的问题及解决方法

使用pyinstaller打包PyQt4程序遇到的问题及解决方法

python pyinstaller pyqt4 打包 QWindows 最近在做课设,用pyqt设计界面。然后用pyinstaller打包程序后,双击运行却总是闪退,后来将exe文件拖...

Python简单日志处理类分享

简单的一个python日志处理类 复制代码 代码如下: #/usr/bin/python #coding=utf-8 import time,types class logsys: &n...

超简单使用Python换脸实例

超简单使用Python换脸实例

换脸! 这段时间,deepfakes搞得火热,比方说把《射雕英雄传》里的朱茵换成了杨幂,看下面的图!毫无违和感! 其实早在之前,基于AI换脸的技术就得到了应用,比方说《速度与激情7》里...

python实现忽略大小写对字符串列表排序的方法

本文实例讲述了python实现忽略大小写对字符串列表排序的方法,是非常实用的技巧。分享给大家供大家参考。具体分析如下: 先来看看如下代码: string = ''' the stir...