python生成验证码

直接上高速

# -*-coding:utf-8 -*-
'''
@Time: 2021/7/29 15:14
@desc: 
'''
from PIL import Image
import random
import time
from io import BytesIO

from PIL import Image, ImageDraw, ImageFont

class CheckCode:

    '''
    生成图片验证码
    '''
    def generation_code(self):
        '''
        生成随机字符
        :return:
        '''
        valid_code = ''
        for i in range(4):
            string_low = chr(random.randint(97, 122))
            string_upper = chr(random.randint(65, 90))
            num = str(random.randint(0,9))
            code = random.choice([string_low, string_upper, num])
            valid_code += code
        return valid_code

    def get_random_color(self):
        '''
        生成随机颜色
        :return:
        '''
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

    def generation_img(self):
        '''
        生成图片
        :return:
        '''
        img = Image.new("RGB", (200, 40), color=self.get_random_color())
        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype('Arial.ttf', size=30)
        check_code = self.generation_code()
        i = 1
        # 写入文本
        for c in check_code:
            draw.text((i*40, 4), c, self.get_random_color(), font=font )
            i = i+1

        # 设置图片宽高
        width = 200
        height = 40

        # 写干扰点
        for i in range(40):
            draw.point([random.randint(0, width), random.randint(0, height)], fill=self.get_random_color())
        # 画线干扰
        for i in range(5):
            x1 = random.randint(0, width)
            x2 = random.randint(0, width)
            y1 = random.randint(0, height)
            y2 = random.randint(0, height)
            draw.line((x1, y1, x2, y2), fill=self.get_random_color())
        # 写干扰圆圈
        for i in range(5):
            draw.point([random.randint(0, width), random.randint(0, height)], fill=self.get_random_color())
            x = random.randint(0, width)
            y = random.randint(0, height)
            draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.get_random_color())

        return img, check_code


img, check_code = CheckCode().generation_img()
# filename = str(int(time.time())) + ".png"
# with open(filename, "wb") as w:
#     img.save(w, format="png")
# 将验证图片写入内存中, 不用存储服务器
f = BytesIO()
img.save(f, "png")
img.show()
print f.getvalue()
print check_code

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值