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)

相关文章

解决vscode python print 输出窗口中文乱码的问题

一、搭建 python 环境 在 VSC 中点击 F1 键,弹出控制台,输入 ext install 界面左侧弹出扩展窗格,输入python,确认,开始搜索 下载发布者为Don Jaya...

Python贪心算法实例小结

本文实例讲述了Python贪心算法。分享给大家供大家参考,具体如下: 1. 找零钱问题:假设只有 1 分、 2 分、五分、 1 角、二角、 五角、 1元的硬币。在超市结账 时,如果 需要...

浅谈Python实现2种文件复制的方法

本文实例主要实现Python中的文件复制操作,有两种方法,具体实现代码如下所示: #coding:utf-8 # 方法1:使用read()和write()模拟实现文件拷贝...

基于Python获取照片的GPS位置信息

基于Python获取照片的GPS位置信息

这篇文章主要介绍了基于Python获取照片的GPS位置信息,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 昨天听人说,用手机拍照会带着...

Pytorch实现GoogLeNet的方法

Pytorch实现GoogLeNet的方法

GoogLeNet也叫InceptionNet,在2014年被提出,如今已到V4版本。GoogleNet比VGGNet具有更深的网络结构,一共有22层,但是参数比AlexNet要少12倍...