美文网首页
生成验证码demo

生成验证码demo

作者: Justforme1 | 来源:发表于2019-05-12 12:41 被阅读0次

from PILimport Image, ImageDraw, ImageFont, ImageFilter

import random

import os

import platform

class VerificationCode(object):

'''用于生成随机验证码'''

    def __init__(self, file_name):

self.str_code = list(range(65,91))

self.str_code += list(range(97,123))

self.str_code += list(range(48,58))

self.file_name = file_name +'.png'

    #  生成随机字符a~z, A~z, 0~9

    def random_str(self):

return str(random.randrange(9))

# 生成随机颜色:

    def random_color(self):

return random.randint(0,245), random.randint(0,245), random.randint(0,245)

# 生成验证码和图片

    def generate_code(self):

# 240 x 60:

        width =60 *4

        height =60

        for iin range(50):

image = Image.new('RGB', (width, height), (255,255,255))

# 根据操作系统获取字体文件

            if platform.uname().system =='Windows':

ttf ='arial.ttf'

            elif platform.uname().system =='Linux':

ttf ='/usr/share/fonts/arial/ARIAL.TTF'

            font = ImageFont.truetype(ttf,50)

draw = ImageDraw.Draw(image)

# 随机生成两条直线(一条贯穿上半部,一条贯穿下半部)

            '''

draw.line((0, 0 + random.randint(0, height // 2),

width, 0 + random.randint(0, height // 2)),

fill=self.random_color())

draw.line((0, height - random.randint(0, height // 2),

width, height - random.randint(0, height // 2)),

fill=self.random_color())

'''

                # 输出文字

            code_str =''

            for tin range(4):

tmp = str(random.randrange(9))

# print(tmp, ord(tmp))

                draw.text((60 * t +10,10), tmp, font=font, fill=self.random_color())

code_str += tmp

# 模糊处理

            print(code_str)

image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)

# 图片保存

            path="D:\\11\\new\\"

            a=str(i)+".jpg"

            path = path + a

image.save(path)

return code_str

if __name__ =='__main__':

ver_code = VerificationCode('验证码')

code = ver_code.generate_code()

a=1

相关文章

网友评论

      本文标题:生成验证码demo

      本文链接:https://www.haomeiwen.com/subject/sghcaqtx.html