python实现验证码-图片类型

1 utils.py

import random


def get_random_code():
    code = ''
    for i in range(5):
        # 随机生成大写字母
        upper_char = chr(random.randint(65, 90))
        lower_char = chr(random.randint(97, 122))
        num_char = str(random.randint(0, 9))
        res = random.choice([upper_char, lower_char, num_char])
        code += res

    return code


def get_random_rgb():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

注意:ttf字体下载

2 生成验证码

from PIL import Image, ImageDraw, ImageFont
from io import BytesIO

import random

from .utils import get_random_code, get_random_rgb


def get_code(request):
    width, hight = 300, 38
    image_tmp = Image.new('RGB', (width, hight), get_random_rgb())
    # 把空图片放在画板上
    draw = ImageDraw.Draw(image_tmp)
    # 加入字体需要去下载哦
    img_font = ImageFont.truetype('./static/font/ss.ttf', 23)
    # 验证码
    code_str = get_random_code()
    for i, item in enumerate(code_str):
        draw.text((20 + i * 45, 0), item, fill=get_random_rgb(), font=img_font)

    # 在图片上画点
    for i in range(50):
        # 画点
        draw.point([random.randint(0, width), random.randint(0, hight)], fill=get_random_rgb())

        # 画弧形
        x = random.randint(0, width)
        y = random.randint(0, hight)

        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_rgb())

    # 在图片上划线
    for i in range(6):
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, hight)
        y2 = random.randint(0, hight)

        # 在图片上画线
        draw.line((x1, y1, x2, y2), fill=get_random_rgb())

    my_io = BytesIO()
    image_tmp.save(my_io, 'png')
    return HttpResponse(my_io.getvalue())

效果图:

在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值