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基于scapy实现修改IP发送请求的方法示例

本文实例讲述了Python基于scapy实现修改IP发送请求的方法。分享给大家供大家参考,具体如下: 今天同事想测试WAF的页面统计功能,所以需要模拟多个IP向多个域名发送请求,也就是需...

Python+tkinter模拟“记住我”自动登录实例代码

Python+tkinter模拟“记住我”自动登录实例代码

本文分享的代码主要是通过Python+tkinter模拟“记住我”自动登录的功能,具体介绍如下。 基本思路:如果某次登录成功,则创建临时文件记录有关信息,每次启动程序时尝试自动获取上次登...

Windows和Linux下使用Python访问SqlServer的方法介绍

经常用Python写demo来验证方案的可行性,最近遇到了Python访问SqlServer的问题,这里总结下。 一、Windows下配置Python访问Sqlserver 环境:Win...

Python生成词云的实现代码

Python生成词云的实现代码

1 概述 利用Python生成简单的词云,需要的工具是cython,wordcloud与anaconda. 2 准备工作 包括安装cython,wordcloud与anaconda. 2...

Python使用修饰器进行异常日志记录操作示例

本文实例讲述了Python使用修饰器进行异常日志记录操作。分享给大家供大家参考,具体如下: 当脚本中需要进行的的相同的异常操作很多的时候,可以用修饰器来简化代码。比如我需要记录抛出的异常...