版权声明:本文系作者原创。未经许可,不得转载。

    
    网站注册时,为了防止机器人自动注册,设置了验证码。本程序可以生成常用的验证码图片。代码如下:

    <verifycation_code.py>

    #!/usr/bin/env python2.7.3

__author__ = 'simba'
# coding=utf-8

import tempfile
import shutil
from image_char import ImageChar
import random
from config import authcode_font  #请确保改字体存在
from app_store.settings import SITE_ROOT
import os

class VerifycationCode(object):
    def destroy(self):
         shutil.rmtree(self.tmpdir, ignore_errors=True)

    def generate(self):
        self.tmpdir = tempfile.mkdtemp()
        self.path = self.tmpdir + "/code.jpg"

        fontColor=(random.randint(0, 255),
                   random.randint(0, 255),
                   random.randint(0, 255))
        size = (100, 40)
        fontPath = os.path.join(SITE_ROOT, authcode_font)
        bgColor = (255, 255, 255)
        fontSize = 20
        charNum = 4
        ic = ImageChar(fontColor, size, fontPath, bgColor, fontSize, charNum)
        self.image_str = ic.RandomString()
        ic.save(self.path)

        return self.image_str, self.path


    <image_char.py>

    #!/usr/bin/env python2.7.3

__author__ = 'simba'
# coding=utf-8

from PIL import Image,ImageDraw,ImageFont
import random
from random_chinese_character import RandomChineseCharacter
from random_letter_number import  RandomLetterNumber

class ImageChar(object):
    def __init__(self, fontColor, size, fontPath, bgColor, fontSize, charNum):
        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)
        self.charNum = charNum

    def __rotate(self):
        self.image.rotate(random.randint(0, 360), 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, max_num):
        draw = ImageDraw.Draw(self.image)
        num = random.randint(1, max_num)
        for i in range(0, num):
            draw.line([self.__randPoint(), self.__randPoint()], self.__randRGB())
        del draw

    def RandomString(self):
        gap = 5
        start = 0
        rand_str = ""
        for i in range(0, self.charNum):
            j = random.randint(0, 1)
            if j == 0:
                char = RandomChineseCharacter.Unicode()
            else:
                char = RandomLetterNumber.LetterNumber()
            rand_str = rand_str + char
            x = start + self.fontSize * i + random.randint(0, gap) + gap * i
            self.__drawText((x, random.randint(-5, 5)), char, self.__randRGB())
            self.__rotate()
        self.__randLine(10)

        return rand_str

    def save(self, path):
        self.image.save(path)


<random_chinese_character.py>

__author__ = 'simba'
# coding=utf-8

import random

class RandomChineseCharacter(object):
    """
    用于随机生成汉字
    汉字的unicode码为[0x4E00, 0x9FBF]
    此处只使用常用汉字
    """
    @staticmethod
    def Unicode():
        code_list = [0x96d5,0x864e,0x7684,0x4e00,0x4e86,0x662f,
                     0x6211,0x4e0d,0x5728,0x4eba,0x4eec,0x6709,
                     0x6765,0x4ed6,0x8fd9,0x4e0a,0x7740,0x4e2a,
                     0x5730,0x5230,0x5927,0x91cc,0x8bf4,0x5c31,
                     0x53bb,0x5b50,0x5f97,0x4e5f,0x548c,0x90a3,
                     0x8981,0x4e0b,0x770b,0x5929,0x65f6,0x8fc7,
                     0x51fa,0x5c0f,0x4e48,0x8d77,0x4f60,0x90fd,
                     0x628a,0x597d,0x8fd8,0x591a,0x6ca1,0x4e3a,
                     0x53c8,0x53ef,0x5bb6,0x5b66,0x53ea,0x4ee5,
                     0x4e3b,0x4f1a,0x6837,0x5e74,0x60f3,0x751f,
                     0x540c,0x8001,0x4e2d,0x5341,0x4ece,0x81ea,
                     0x9762,0x524d,0x5934,0x9053,0x5b83,0x540e,
                     0x7136,0x8d70,0x5f88,0x50cf,0x89c1,0x4e24,
                     0x7528,0x5979,0x56fd,0x52a8,0x8fdb,0x6210,
                     0x56de,0x4ec0,0x8fb9,0x4f5c,0x5bf9,0x5f00,
                     0x800c,0x5df1,0x4e9b,0x73b0,0x5c71,0x6c11,
                     0x5019,0x7ecf,0x53d1,0x5de5,0x5411,0x4e8b,
                     0x547d,0x7ed9,0x957f,0x6c34,0x51e0,0x4e49,
                     0x4e09,0x58f0,0x4e8e,0x9ad8,0x624b,0x77e5,
                     0x7406,0x773c,0x5fd7,0x70b9,0x5fc3,0x6218,
                     0x4e8c,0x95ee,0x4f46,0x8eab,0x65b9,0x5b9e,
                     0x5403,0x505a,0x53eb,0x5f53,0x4f4f,0x542c,
                     0x9769,0x6253,0x5462,0x771f,0x5168,0x624d,
                     0x56db,0x5df2,0x6240,0x654c,0x4e4b,0x6700,
                     0x5149,0x4ea7,0x60c5,0x8def,0x5206,0x603b,
                     0x6761,0x767d,0x8bdd,0x4e1c,0x5e2d,0x6b21,
                     0x4eb2,0x5982,0x88ab,0x82b1,0x53e3,0x653e,
                     0x513f,0x5e38,0x6c14,0x9ec4,0x4e94,0x7b2c,
                     0x4f7f,0x5199,0x519b,0x6728,0x73cd,0x5427,
                     0x6587,0x8fd0,0x518d,0x679c,0x600e,0x5b9a,
                     0x8bb8,0x5feb,0x660e,0x884c,0x56e0,0x522b,
                     0x98de,0x5916,0x6811,0x7269,0x6d3b,0x90e8,
                     0x95e8,0x65e0,0x5f80,0x8239,0x671b,0x65b0,
                     0x5e26,0x961f,0x5148,0x529b,0x5b8c,0x5374,
                     0x7ad9,0x4ee3,0x5458,0x673a,0x66f4,0x4e5d,
                     0x60a8,0x6bcf,0x98ce,0x7ea7,0x8ddf,0x7b11,
                     0x554a,0x5b69,0x4e07,0x5c11,0x76f4,0x610f,
                     0x591c,0x6bd4,0x9636,0x8fde,0x8f66,0x91cd,
                     0x4fbf,0x6597,0x9a6c,0x54ea,0x5316,0x592a,
                     0x6307,0x53d8,0x793e,0x4f3c,0x58eb,0x8005,
                     0x5e72,0x77f3,0x6ee1,0x6885,0x65e5,0x51b3,
                     0x767e,0x539f,0x62ff,0x7fa4,0x7a76,0x5404,
                     0x516d,0x672c,0x601d,0x89e3,0x7acb,0x6cb3,
                     0x6751,0x516b,0x96be,0x65e9,0x8bba,0x5417,
                     0x6839,0x5171,0x8ba9,0x76f8,0x7814,0x4eca,
                     0x5176,0x4e66,0x5750,0x63a5,0x5e94,0x5173,
                     0x4fe1,0x89c9,0x6b65,0x53cd,0x5904,0x8bb0,
                     0x5c06,0x5343,0x627e,0x4e89,0x9886,0x6216,
                     0x5e08,0x7ed3,0x5757,0x8dd1,0x8c01,0x8349,
                     0x8d8a,0x5b57,0x52a0,0x811a,0x7d27,0x7231,
                     0x7b49,0x4e60,0x9635,0x6015,0x6708,0x9752,
                     0x534a,0x706b,0x6cd5,0x9898,0x5efa,0x8d76,
                     0x4f4d,0x5531,0x6d77,0x4e03,0x5973,0x4efb,
                     0x4ef6,0x611f,0x51c6,0x5f20,0x56e2,0x5c4b,
                     0x79bb,0x8272,0x8138,0x7247,0x79d1,0x5012,
                     0x775b,0x5229,0x4e16,0x521a,0x4e14,0x7531,
                     0x9001,0x5207,0x661f,0x5bfc,0x665a,0x8868,
                     0x591f,0x6574,0x8ba4,0x54cd,0x96ea,0x6d41,
                     0x672a,0x573a,0x8be5,0x5e76,0x5e95,0x6df1,
                     0x523b,0x5e73,0x4f1f,0x5fd9,0x63d0,0x786e,
                     0x8fd1,0x4eae,0x8f7b,0x8bb2,0x519c,0x53e4,
                     0x9ed1,0x544a,0x754c,0x62c9,0x540d,0x5440,
                     0x571f,0x6e05,0x9633,0x7167,0x529e,0x53f2,
                     0x6539,0x5386,0x8f6c,0x753b,0x9020,0x5634,
                     0x6b64,0x6cbb,0x5317,0x5fc5,0x670d,0x96e8,
                     0x7a7f,0x5185,0x8bc6,0x9a8c,0x4f20,0x4e1a,
                     0x83dc,0x722c,0x7761,0x5174,0x5f62,0x91cf,
                     0x54b1,0x89c2,0x82e6,0x4f53,0x4f17,0x901a,
                     0x51b2,0x5408,0x7834,0x53cb,0x5ea6,0x672f,
                     0x996d,0x516c,0x65c1,0x623f,0x6781,0x5357,
                     0x67aa,0x8bfb,0x6c99,0x5c81,0x7ebf,0x91ce,
                     0x575a,0x7a7a,0x6536,0x7b97,0x81f3,0x653f,
                     0x57ce,0x52b3,0x843d,0x94b1,0x7279,0x56f4,
                     0x5f1f,0x80dc,0x6559,0x70ed,0x5c55,0x5305,
                     0x6b4c,0x7c7b,0x6e10,0x5f3a,0x6570,0x4e61,
                     0x547c,0x97f3,0x7b54,0x54e5,0x9645,0x65e7,
                     0x795e,0x5ea7,0x7ae0,0x5e2e,0x5566,0x53d7,
                     0x7cfb,0x4ee4,0x8df3,0x975e,0x4f55,0x725b,
                     0x53d6,0x5165,0x5cb8,0x6562,0x6389,0x5ffd,
                     0x79cd,0x88c5,0x9876,0x6025,0x6234,0x6797,
                     0x505c,0x606f,0x53e5,0x533a,0x8863,0x822c,
                     0x62a5,0x53f6,0x538b,0x6162,0x53d4,0x80cc,
                     0x7ec6,0x8273,0x4f50]

        var = random.choice(code_list)

        return unichr(var)


<random_letter_number.py>

#!/usr/bin/env python2.7.3

__author__ = 'simba'
# coding=utf-8

import random
import string

class RandomLetterNumber(object):
    """
    用于随机生成数字和字母
    """
    @staticmethod
    def LetterNumber():
        allw = string.ascii_letters + string.digits
        letter_number = random.choice(allw)

        return letter_number

<config.py>

authcode_font = "static/fonts/wqy-microhei.ttc"


使用方式举例,在django的view文件中使用:

def verify_code(request):
    vc = VerifycationCode()
    image_code, image_path = vc.generate()
    f = open(image_path, "r")
    buffer = f.read()
    f.close()
    vc.destroy()
    httpResponse = HttpResponse(content=buffer)
    request.session['auth_code'] = image_code.lower() #校验码不区分大小写
    return httpResponse


注:该程序需要用到PIL模块,必须先安装libfreetype6-dev、libfreetype6、libjpeg8-dev、libjpeg8,
    即: $ sudo apt-get install ibfreetype6-dev libfreetype6 libjpeg8-dev libjpeg8;
然后再安装Pillow包,
    即:$ pip install Pillow。
先后顺序不能改,否则PIL无法使用。

lansheng228
256 声望4 粉丝