python生成随机的图片验证码

class MyView(View):
    def get(self, request):
        # 创建一个画布
        img = Image.new('RGB', (200, 100), (0, 50, 200))

        # 创建一个画笔,并绑定画布
        img_draw = ImageDraw.Draw(img, 'RGB')

        # 创建一个字体,需要指定STATICFILES_DIRS = [ os.path.join(BASE_DIR,'statics')]
        font = ImageFont.truetype('statics/gb.ttf', size=50, encoding='utf-8')

        # 画什么东西,fill填充字体的颜色
        img_draw.text((15, 25), "hello world", fill=(100, 100, 100), font=font)
        for i in range(200):
            img_draw.point((random.randint(0,200), random.randint(0,100)),fill=(random.randint(0,255), random.randint(0,255), random.randint(0,255)))
        
        # 写入内容带内存缓冲区中,buffer相当于一个文件对象
        from io import BytesIO
        buffer = BytesIO()
        img.save(buffer, 'png')
        content = buffer.getvalue()

        return HttpResponse(content, content_type='image/png')

Python中,生成随机图形验证码通常涉及到图像处理库,如PIL(Python Imaging Library)或其更新版本Pillow,以及可能用到的随机数生成库如random和numpy。以下是一个简单的步骤概述: 1. 导入所需的库: ```python from PIL import Image, ImageDraw, ImageFont import random import numpy as np ``` 2. 定义图形元素,如线条、圆形、矩形、字母和数字: ```python def draw_random_shape(size, shapes): shape = random.choice(shapes) if shape == 'line': draw.line((random.randint(0, size), random.randint(0, size)), (random.randint(0, size), random.randint(0, size)), fill=(0, 0, 0)) elif shape == 'circle': center = (random.randint(0, size), random.randint(0, size)) draw.ellipse((center-10, center-10, center+10, center+10), fill=(0, 0, 0)) # 添加其他形状,如矩形等 def generate_text(): return ''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=random.randint(4, 6))) ``` 3. 创建验证码图像: ```python size = 100 image = Image.new('RGB', (size, size), color='white') draw = ImageDraw.Draw(image) shapes = ['line', 'circle', 'rectangle'] # 可自定义形状列表 for _ in range(random.randint(4, 6)): draw_random_shape(size, shapes) text = generate_text() font = ImageFont.truetype("arial.ttf", size=random.randint(20, 30)) # 加载字体 text_position = (random.randint(10, size-10), random.randint(10, size-10)) draw.text(text_position, text, font=font, fill=(0, 0, 0)) # 保存验证码图片 image.save('captcha.png') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值