一、前言
有次在路边看见有的车前挡风玻璃上贴了一张二维码图片,上面写着“挪车请扫二维码”,手机一扫就出现了车主手机号码,于是乎就尝试使用Python来生成二维码图片
二、准备
生成二维码使用qrcode库,预览二维码图片使用matplotlib库,读取图片使用PIL,第三方库,需要提前安装
pip install qrcode
pip install matplotlib
pip install pillow
三、生成二维码图片
使用qrcode.make,传入二维码信息即可,再使用matplotlib的pyplot.imshow预览图片
import qrcode
from matplotlib import pyplot as plt
if __name__ == '__main__':
# 生成二维码图片
img1 = qrcode.make('Old Driver, Please Take Me')
# 预览图片
fig = plt.figure("qr_img") # 创建图像
plt.imshow(img1) # 加载图片
plt.axis("off") # 隐藏坐标系
plt.show() # 显示图片
# 保存图片
img1.save('qr_img.png')
运行效果:
这里使用matplotlib预览的二维码图片背景为黄色,实际图片背景色为白色,暂未找到原因
四、自定义二维码图片
直接生成的二维码图片很普通,下面就来自定义二维码图片的样式
根据官方文档,自定义设置需要先生成qr实例,再传入相应的参数
设置背景图片
bg.png为背景图片
import qrcode
from matplotlib import pyplot as plt
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.colormasks import ImageColorMask
if __name__ == '__main__':
# 生成二维码图片
qr = qrcode.QRCode() # 生成qr实例
qr.add_data('Old Driver, Please Take Me') # 添加二维码信息
img2 = qr.make_image(image_factory=StyledPilImage,
color_mask=ImageColorMask(color_mask_path='bg.png')) # 设置二维码样式和背景图片
# 预览图片
fig = plt.figure("qr_img") # 创建图像
plt.imshow(img2) # 加载图片
plt.axis("off") # 隐藏坐标系
plt.show() # 显示图片
运行效果:
设置渐变二维码
import qrcode
from matplotlib import pyplot as plt
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.colormasks import SquareGradiantColorMask
from qrcode.image.styles.moduledrawers import GappedSquareModuleDrawer
if __name__ == '__main__':
# 生成二维码图片
qr = qrcode.QRCode() # 生成qr实例
qr.add_data('Old Driver, Please Take Me') # 添加二维码信息
img2 = qr.make_image(image_factory=StyledPilImage, module_drawer=GappedSquareModuleDrawer(),
color_mask=SquareGradiantColorMask()) # 设置二维码样式和渐变色
# 预览图片
fig = plt.figure("qr_img") # 创建图像
plt.imshow(img2) # 加载图片
plt.axis("off") # 隐藏坐标系
plt.show() # 显示图片
运行效果:
设置中心图片
添加设置中心图片的方法,生成二维码时调用即可
def set_center_img(center_img_path, qr_img):
img = Image.open(center_img_path) # 读取图片
qr_img_width, qr_img_height = qr_img.size # 获取二维码图片的宽高
target_width, target_height = qr_img_width // 8, qr_img_height // 8 # 设置中心图片目标宽高
center_img = img.resize((target_width, target_height), Image.BILINEAR) # 调整中心图片的尺寸(使用双线性插值法)
center_img_x, center_img_y = (qr_img_width - target_width) // 2, (
qr_img_height - target_height) // 2 # 中心图片在二维码图片上的坐标
qr_img.paste(center_img, (center_img_x, center_img_y)) # 将调整后的图片粘贴到二维码图片中心
if __name__ == '__main__':
# 生成二维码图片
qr = qrcode.QRCode() # 生成qr实例
qr.add_data('Old Driver, Please Take Me') # 添加二维码信息
img2 = qr.make_image(image_factory=StyledPilImage, module_drawer=GappedSquareModuleDrawer(),
color_mask=SquareGradiantColorMask()) # 设置二维码样式和渐变色
# 设置中心图片
set_center_img('Spongebob.png', img2)
# 预览图片
fig = plt.figure("qr_img") # 创建图像
plt.imshow(img2) # 加载图片
plt.axis("off") # 隐藏坐标系
plt.show() # 显示图片
运行效果: