一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

整理Python生成随机中文图片验证码源代码

时间:2015-01-15 编辑:简简单单 来源:一聚教程网

在登录很多网站的时候,他们已经不在使用简单的英文和数字的验证码,为了防止恶心注册和群发软件的侵袭,现在都开始使用中文的验证码了。

今天我们就跟大家分享一段用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生成验证码(webpy完整验证码类)

python生成验证码可以使用成熟的wheezy.captcha,首先需要安装PIL包 easy_install PIL, 然后需要安装wheezy.captcha easy_install wheezy.captcha

安装之后生成验证码就很简单了:

 

 代码如下 复制代码

captcha_image_t = captcha(drawings=[
    background(),
    text(fonts=[
        path.join(_fontsDir,'78640___.ttf'),
        path.join(_fontsDir,'andyb.ttf')],
        drawings=[
            warp(),
            rotate(),
            offset()
        ]),
    curve(),
    noise(),
    smooth()
])
chars_t = random.sample(_chars, 4)

image_t = captcha_image_t(chars_t)
image_t.save('test.jpeg','jpeg',quality=75)

 

验证码效果图如下:

验证码captcha

验证码captcha

完整的webpy生成验证码类实现如下:

 

 代码如下 复制代码

#!/usr/bin/env python
# coding: utf-8

__author__ = 'outofmemory.cn'

from wheezy.captcha.image import captcha

from wheezy.captcha.image import background
from wheezy.captcha.image import curve
from wheezy.captcha.image import noise
from wheezy.captcha.image import smooth
from wheezy.captcha.image import text

from wheezy.captcha.image import offset
from wheezy.captcha.image import rotate
from wheezy.captcha.image import warp

import random
import web

from os import path
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO

if __name__ == '__main__':
    import os,sys
    webPath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.insert(0,webPath)

from run import session

_controllersDir = path.abspath(path.dirname(__file__))
_webDir = path.dirname(_controllersDir)
_fontsDir = path.join(path.dirname(_webDir),'fonts')

_chars = 'ABCDEFJHJKLMNPQRSTUVWXY3456789'

SESSION_KEY_CAPTCHA = 'captcha'

def isValidCaptcha(captchaInputName='captcha'):
    userInputVal = web.input().get(captchaInputName)
    if not userInputVal: return False
    correctVal = session[SESSION_KEY_CAPTCHA]
    return userInputVal.upper() == correctVal

class Captcha:
    '''验证码'''

    def GET(self):
        captcha_image = captcha(drawings=[
            background(),
            text(fonts=[
                path.join(_fontsDir,'78640___.ttf'),
                path.join(_fontsDir,'andyb.ttf')],
                drawings=[
                    warp(),
                    rotate(),
                    offset()
                ]),
            curve(),
            noise(),
            smooth()
        ])
        chars = random.sample(_chars, 4)
        session[SESSION_KEY_CAPTCHA] = ''.join(chars)
        image = captcha_image(chars)
        out = StringIO()
        image.save(out,"jpeg",quality=75)
        web.header('Content-Type','image/jpeg')
        return out.getvalue()

if __name__ == '__main__':
    print _fontsDir
    captcha_image_t = captcha(drawings=[
        background(),
        text(fonts=[
            path.join(_fontsDir,'78640___.ttf'),
            path.join(_fontsDir,'andyb.ttf')],
            drawings=[
                warp(),
                rotate(),
                offset()
            ]),
        curve(),
        noise(),
        smooth()
    ])
    chars_t = random.sample(_chars, 4)

    image_t = captcha_image_t(chars_t)
    image_t.save('test.jpeg','jpeg',quality=75)

 

程序中使用的字体文件要放在web目录同级的fonts目录下,程序中的两个字体文件都是复制的windows字体,在linux下可以正常使用,要注意扩展名的大小写。

热门栏目