1. 图形验证码库 captcha
# 引入图形库
from captcha.image import ImageCaptcha
# 获取图像对象
image = ImageCaptcha(width=120, height=40, font_sizes=(30, 32, 36))
chars = "1234"
# 创建二维码对象
im = image.generate(chars)
# (1) 直接取值
img_val = im.getvalue()
# (2) 保存文件
file_name = "1.png"
im.save(file_name)
2. 二维码库 qrcode
import qrcode
import os
# 创建二维码图像 err_level 0-3 错误由高到低 size每格像素大小
def make_qrcode(url="test", file_name="", size=8, err_level=0):
if err_level == 3:
error_correction = qrcode.constants.ERROR_CORRECT_L
elif err_level == 2:
error_correction = qrcode.constants.ERROR_CORRECT_M
elif err_level == 1:
error_correction = qrcode.constants.ERROR_CORRECT_Q
else:
error_correction = qrcode.constants.ERROR_CORRECT_H
# 初始化二维码对象
qr = qrcode.QRCode(
version=1,
error_correction=error_correction,
box_size=size,
border=4,
)
# 添加要生成二维码的连接
qr.add_data(url)
qr.make(fit=True)
file_content = file_name
# 设置填充颜色与背景色
img = qr.make_image(fill_color="black", back_color="white")
# 是否要保存文件
if file_name and isinstance(file_name, str):
# 保存文件
img.save(file_name)
else:
# 直接输出
b = io.BytesIO()
img.save(b, "PNG")
file_content = b.getvalue()
return file_content
# 直接调用即可