基于Python Pillow库生成随机验证码

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import random

class ValidCodeImg:
    """
        可以生成一个经过降噪后的随机验证码的图片
        :param width: 图片宽度 单位px
        :param height: 图片高度 单位px
        :param code_count: 验证码个数
        :param font_size: 字体大小
        :param point_count: 噪点个数
        :param line_count: 划线个数
        :param img_format: 图片格式
    """
    __str = ""
    def __init__(self, width=150, height=30, code_count=5, font_size=32, point_count=20, line_count=3, img_format='png'):
        image = Image.new('RGB', (width, height), self.getRandomColor())
        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype('kumo.ttf', size=font_size)
        for i in range(code_count):
            random_str = self.getRandomStr()
            self.__str += random_str
            draw.text((10 + i * height, 0), random_str, self.getRandomColor(), font=font)
        for i in range(line_count):
            x1 = random.randint(0, width)
            y1 = random.randint(0, height)
            x2 = random.randint(0, width)
            y2 = random.randint(0, height)
            draw.line((x1, y1, x2, y2), fill=self.getRandomColor())
        for i in range(point_count):
            draw.point([random.randint(0, width), random.randint(0, height)], fill=self.getRandomColor())
            x = random.randint(0, width)
            y = random.randint(0, height)
            draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.getRandomColor())
        image.save(open('test.%s'%img_format, 'wb'), img_format)
    def getstr(self):
        return self.__str
    def getRandomColor(self):
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
    def getRandomStr(self):
        random_number = str(random.randint(0, 9))
        random_low_alpha = chr(random.randint(97, 122))
        random_uppper_alpha = chr(random.randint(65, 90))
        return random.choice([random_number, random_low_alpha, random_uppper_alpha])
View Code

其中ImageFont.truetype()的第一个参数为字体类型, 需为用户有的*.ttf格式的字体文件。

效果:

猜你喜欢

转载自www.cnblogs.com/sqdtss/p/9439271.html