Python 生成验证码

得意时要看淡,失意时要看开。不论得意失意,切莫大意;不论成功失败,切莫止步。志得意满时,需要的是淡然,给自己留一条退路;失意落魄时,需要的是泰然,给自己觅一条出路Python 生成验证码,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

# !/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author  : v_jiaohaicheng@baidu.com
@des     : 生成四位字符串验证码图片
		(传入长度为四的验证码列表)

"""
import os
import random
from io import BytesIO
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont


class Verify():

    def __init__(self):
        pass

    def random_color(self,nums=3):
        random_num_lists = []
        while nums > 0:
            random_num = random.randint(0, 255)
            random_num_lists.append(random_num)
            nums -= 1
        return tuple(random_num_lists)

    def generate_picture(self,width=120, height=35):
        image = Image.new('RGB', (width, height), self.random_color())
        return image

    def random_str(self):
        '''
        获取一个随机字符, 数字或小写字母
        :return:
        '''
        random_num = str(random.randint(0, 9))
        random_low_alpha = chr(random.randint(97, 122))
        random_char = random.choice([random_num, random_low_alpha])
        return random_char

    def draw_str(self,count, image, font_size,rand_str_lis=[]):
        """
        在图片上写随机字符
        :param count: 字符数量
        :param image: 图片对象
        :param font_size: 字体大小
        :return:
        """
        draw = ImageDraw.Draw(image)
        # 获取一个font字体对象参数是ttf的字体文件的目录,以及字体的大小
        font_file = os.path.join(R"C:\Windows\Fonts\simkai.ttf")
        font = ImageFont.truetype(font_file, size=font_size)
        temp = []
        for i in range(count):
            random_char = str(rand_str_lis[i])
            draw.text((10+i*30, -2), random_char, self.random_color(), font=font)
            temp.append(random_char)
        valid_str = "".join(temp)
        return valid_str, image


    def noise(self,image, width=120, height=35, line_count=3, point_count=20):
        '''

        :param image: 图片对象
        :param width: 图片宽度
        :param height: 图片高度
        :param line_count: 线条数量
        :param point_count: 点的数量
        :return:
        '''
        draw = ImageDraw.Draw(image)
        for i in range(line_count):
            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.random_color())

            # 画点
            for i in range(point_count):
                draw.point([random.randint(0, width), random.randint(0, height)], fill=self.random_color())
                x = random.randint(0, width)
                y = random.randint(0, height)
                draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.random_color())

        return image

    def main(self,rand_str_lis):
        image = self.generate_picture()
        valid_str, image = self.draw_str(4, image, 35,rand_str_lis)
        image = self.noise(image)
        image.save('test.png')

        f = BytesIO()
        image.save(f, 'png')  # 保存到BytesIO对象中, 格式为png
        data = f.getvalue()
        f.close()
        return valid_str, data


if __name__ == '__main__':
    vy = Verify()
    rand_str_lis = ["1", "2", "3r", "2"]
    verify,data = vy.main(rand_str_lis)

    print(verify)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/156879.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!