pillow模块和开箱即用的python生成验证码

pillow模块

安装:pip install Pillow

PNG :是四通道 RGBA 模式,即红色、绿色、蓝色、Alpha 透明色

JPG: 是三通道 RGB 模式。

Image

Image是Pillow中最为重要的类,实现了Pillow中大部分的功能。要创建这个类的示例主要有三个方法:

  1. 从文件加载图片
  2. 处理其他图像获得
  3. 创建一个新的图像
from PLI import Image

# 打开图片
img = Image.open('test.png')

# 创建图片(模式,(长,宽),填充颜色)
img = Image.new('RGB', (200, 100), 'red')
img = Image.new('RGBA',(200,100),(255,255,255,0))

mode 是一个字符串,它定义图像中像素的类型和深度。每个像素使用位深度的全部范围。所以1位像素的范围是0-18位像素的范围是0-255,依此类推。当前版本支持以下标准模式:
11位黑白像素,每字节存储一个像素)
L (8位像素,黑白)
P (8位像素,使用调色板映射到任何其他模式)
RGB (3x8位像素,真彩色)
RGBA (4x8位像素,带透明蒙版的真彩色)
CMYK (4x8位像素,分色)
YCbCr (3x8位像素,彩色视频格式)
LAB (3x8位像素,L*A*B颜色空间)
HSV (3x8位像素、色调、饱和度、值颜色空间)
I (32位有符号整数像素)
F (32位浮点像素)

# 展示图片
img.show()

# 保存图片
img.save('test.png')

# 获取文件名
print(img.filename)

# 获取图片大小size(height,width)
print(img.size)
print(img.height)
print(img.width)

# 获取图片模式
print(img.mode)
>>> RGB

# 获取图片格式
print(img.format)
>>> PNG

# 获取图片信息
print(img.info)

# 图片转换png-->jpg
image=im.convert('RGB')

ImageDraw

PIL.ImageDraw 模块提供了一系列的绘图方法,通过该模块可以创建一个新的图形,或者在现有的图像上再绘制一个图形,从而起到对原图注释和修饰的作用。

from PIL import ImageDraw

draw = ImageDraw.Draw(im)

ImageFont

PIL.ImagreFont 模块通过加载不同格式的字体文件,从而在图像上绘制出不同类型的文字,比如 TrueType 和 OpenType 类型的字体。

from PIL import ImageFont

font = ImageFont.truetype(font='字体文件路径', size=字体大小)

绘制字体

# text()方法用于绘制字体

draw.text((x,y), "text", font, fill)
(x,y) 表示添加文本的起始坐标位置;
text:字符串格式,要添加的文本内容;
font:ImageFont 对象;
fill:文本填充颜色。

生成gif图

GIF(Graphics Interchange Format,图形交换格式)是一种“位图”图像格式,它以.gif作为图像的扩展名。GIF 图片非常适合在互联网中使用,这是因为它采用了图像预压缩技术,该技术的应用,在一定程度上减少了图像传播、加载所消耗的时间。

frames = [imgObj1,imgObj2,imgObj3,imgObj4,imgObj5]

# 以imgObj1开始合并
frames[0].save(
'rainafter.gif',save_all=True,append_images=frames[1:],transparency=0,duration=2000,loop=0,disposal=2)

save_all:保存所有图像
append_images:追加图像列表
transparency:设置透明背景色
duration:单位毫秒,动画持续时间
loop=0:无限循环
disposal=2:恢复原背景颜色。

python生成验证码 开箱即用

验证码类

import string
import random
from PIL import Image, ImageDraw, ImageFont


class Captcha:
    def __init__(self, captcha_size=(150, 50),
                 font_size=40, font_style=None, text_number=6,
                 line_number=6, background_color=(255, 255, 255),
                 sources=None):
        """
        :param captcha_size: 验证码Size:tuple
        :param font_size:    字体Size:int
        :param font_style:   字体样式:ttf文件路径
        :param text_number:  验证码数量:int
        :param line_number:  干扰线条数量:int
        :param background_color: 验证码背景:rgb
        :param sources:      验证码源:str
        """
        self.captcha_width = captcha_size[0]
        self.captcha_height = captcha_size[-1]
        self.font_size = font_size
        self.text_number = text_number
        self.line_number = line_number
        self.background_color = background_color
        if font_style:
            self.font_style = font_style
        else:
            self.font_style = 'simkai.ttf'
        if sources:
            self.sources = sources
        else:
            self.sources = string.ascii_letters + string.digits

    def _get_text(self):
        text = random.sample(self.sources, k=self.text_number)
        return ''.join(text)

    def _font_color(self):
        return random.randint(0, 150), random.randint(0, 150), random.randint(0, 150)

    def _other_color(self):
        return random.randint(0, 250), random.randint(0, 250), random.randint(0, 250)

    def _draw_line(self, draw):
        begin = (random.randint(0, self.captcha_width // 2), random.randint(0, self.captcha_height // 2))
        end = (random.randint(self.captcha_width // 2, self.captcha_width),
               random.randint(self.captcha_height // 2, self.captcha_height))
        draw.line([begin, end], fill=self._other_color())

    def _draw_point(self, draw, point_chance):
        for w in range(self.captcha_width):
            for h in range(self.captcha_height):
                tmp = random.randint(0, 100)
                if tmp < point_chance:
                    draw.point((w, h), fill=self._other_color())

    def _draw_text(self, draw, text, font, spacing=20):
        """
        :param draw: 画布对象:ImageDraw
        :param text: 验证码:str
        :param font: 字体对象:ImageFont
        :param spacing: 验证码间隙:int
        """
        # 使用该字体画出来的字符串大小,与字体大小有关
        text_width, text_height = font.getsize(text)

        char_length = int(text_width / self.text_number)
        # 空白之和
        total_spacing = (self.text_number - 1) * spacing
        # 有效区域
        true_width = total_spacing + text_width
        true_height = text_height

        if true_width >= self.captcha_width:
            raise ValueError('字体加中间空隙超过图片总宽度')

        start_width = int((self.captcha_width - true_width) / 2)
        start_height = int((self.captcha_height - true_height) / 2)
        for value in text:
            position = start_width, start_height
            draw.text(position, value, font=font, fill=self._font_color())
            start_width = start_width + char_length + spacing

    def code(self):
        captcha = Image.new('RGB', (self.captcha_width, self.captcha_height), self.background_color)
        font = ImageFont.truetype(self.font_style, self.font_size)
        draw = ImageDraw.Draw(captcha)
        text = self._get_text()

        self._draw_text(draw, text, font, spacing=5)

        for _ in range(self.line_number):
            self._draw_line(draw)

        # 每个坐标的画点概率10%
        self._draw_point(draw, 10)
        return captcha, text

调用

if __name__ == '__main__':
    captcha = Captcha()
    imgObj, code = a.code()
    imgObj.save('test.png')

结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Generalzy

文章对您有帮助,倍感荣幸

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值