python3用pillow生成验证码,tornado中输出图片

本文介绍了一个使用Python和PIL库实现的验证码生成器类。该类可以生成包含字母和线条的图片验证码,并提供了多种定制选项,如背景颜色、字体大小等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

验证码生成类:

from PIL import Image,ImageDraw, ImageFont, ImageFilter
import random

class VerifyCode():

    def __init__(self):
        self._letter_cases = 'abcdefghjkmnpqrstuvwxy'
        self._upper_cases = self._letter_cases.upper()
        self._numbers = ''.join(map(str, range(3, 10)))
        pass

    def createCodeImage(self,size=(120,30),img_type='jpg',
                        mode='RGB',bg_color=(255,255,255),fg_color=(0,0,255),
                            font_size=18,font_type='arial.ttf',
                            length=4,draw_lines=True,n_line=(1,2),
                            draw_points=True,point_chance=2):
        width,height = size;
        img = Image.new(mode, size, bg_color);
        draw = ImageDraw.Draw(img)

        def get_chars():
            return random.sample(self._letter_cases,length)

        def creat_line():
            line_num = random.randint(*n_line)#sign that the param is a list

            for i in range(line_num):
                begin = (random.randint(0, size[0]), random.randint(0, size[1]))
                end = (random.randint(0, size[0]), random.randint(0, size[1]))
                draw.line([begin, end], fill=(0, 0, 0))

        def create_points():
            chance = min(100, max(0, int(point_chance)))
            for w in range(width):
                for h in range(height):
                    tmp = random.randint(0, 100)
                    if tmp > 100 - chance:
                        draw.point((w, h), fill=(0, 0, 0))



        def create_strs():
            c_chars = get_chars()
            strs = ' %s ' % ' '.join(c_chars)
            font = ImageFont.truetype(font_type, font_size)
            font_width, font_height = font.getsize(strs)
            draw.text(((width - font_width) / 3, (height - font_height) / 3),
                        strs, font=font, fill=fg_color)
            return ''.join(c_chars)



        if draw_lines:
            creat_line()
        if draw_points:
            create_points()
        strs = create_strs()

        params = [1 - float(random.randint(1, 2)) / 100,
                  0,
                  0,
                  0,
                  1 - float(random.randint(1, 10)) / 100,
                  float(random.randint(1, 2)) / 500,
                  0.001,
                  float(random.randint(1, 2)) / 500
                  ]
        img = img.transform(size, Image.PERSPECTIVE, params)
        img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
        return img, strs
#
# if __name__ == '__main__':
#     code_img,capacha_code= creat_validata_code()
#     code_img.save('xx.jpg','JPEG')

控制器如下:

#coding:utf-8
import tornado.httpserver
import tornado.ioloop
import tornado.process
import tornado.web
from app.common.VerifyCode import *
from app.web.base.BaseHandler import BaseHandler
from io import BytesIO
class verifyCode(BaseHandler):
    def get(self, *args, **kwargs):
        #self.write("go back")
        #self.render("admin/index.mako")
        vecode=VerifyCode()

        code_img,capacha_code= vecode.createCodeImage();
        #self.write(capacha_code)
        msstream=BytesIO()
        code_img.save(msstream,"jpeg")
        code_img.close()
        self.set_header('Content-Type', 'image/jpg')
        self.write(msstream.getvalue())


    def post(self, *args, **kwargs):
        self.get(self,args,kwargs)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值