安装引用
pip install qrcode
pip install Pillow
引用
from PIL import Image
import qrcode
设置二维码
# 最小尺寸 1 会生成 21 * 21 的二维码,version 每增加 1,生成的二维码就会添加 4 尺寸
# version :QR code 的版次,可以设置 1 ~ 40 的版次。
# 参数 error_correction 指定二维码的容错系数,分别有以下4个系数:
# ERROR_CORRECT_L: 7%的字码可被容错
# ERROR_CORRECT_M: 15%的字码可被容错
# ERROR_CORRECT_Q: 25%的字码可被容错
# ERROR_CORRECT_H: 30%的字码可被容错
# 参数 box_size 表示二维码里每个格子的像素大小
# 参数 border 表示边框的格子厚度是多少(默认是4)
qr = qrcode.QRCode(version=3, box_size=10, border=4, error_correction=qrcode.constants.ERROR_CORRECT_H)
# 添加数据
# 可以是文本,url
qr.add_data(content)
# 填充数据
qr.make(fit=True)
# 生成图片
# fill_color 二维码颜色
# back_color 背景颜色
img = qr.make_image(fill_color="green", back_color="white")
img = img.convert('RGBA')
img.show()
二维码中间添加logo图片
# 设置 logo 大小和位置
icon = Image.open(logoPath)
icon = icon.convert('RGBA')
w, h = img.size
# logo 大小参数
factor = 4
size_w = int(w / factor)
size_h = int(h / factor)
icon_w, icon_h = icon.size
if icon_w > size_w:
icon_w = size_w
if icon_h > size_h:
icon_h = size_h
# 重置logo尺寸
icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
# 居中显示坐标
w = int((w - icon_w) / 2)
h = int((h - icon_h) / 2)
# 粘贴到二维码指定位置
# im:源图像或像素值(整数或元组)。
# box:一个可选的4元组,用于指定要粘贴到的区域。
# 如果使用2元组,则将其视为左上角。
# 如果忽略或无,则源将粘贴到左上角。
# 如果给定图像作为第二个参数,而没有第三个参数,则框默认为(0,0),第二个自变量被解释为掩码图像。
# mask:可选的掩码图像。
img.paste(icon, (w, h), mask=None)
img.show()
保存二维码到本地
# quality -- 图片保存质量 默认为 100 设置该参数可以对目标文件字节数进行调整
img.save(path, quality=100)