第一种: 生成纯文本的二维码;
import qrcode # 这里使用的python的库 qrcode 当然qrcode 是依赖pillow库的, 所以第一步当然是安装相关的模块 pip install qrcode def make_code(): """ ERROR_CORRECT_L:大约7%或更少的错误能被纠正。 ERROR_CORRECT_M(默认):大约15%或更少的错误能被纠正。 ROR_CORRECT_H:大约30%或更少的错误能被纠正。 """ url = 'https://www.luffycity.com' qr = qrcode.QRCode( version=None, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=2, ) qr.add_data(url) qr.make(fit=True) img = qr.make_image() img.save('二维码.png') make_code()
第二种, 生成带有logo 图标的二维码;
from PIL import Image import qrcode def make_code(): url = 'https://www.luffycity.com' qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=8, border=4) qr.add_data(url) qr.make(fit=True) img = qr.make_image() img = img.convert("RGBA") icon = Image.open("logo.png") img_w, img_h = img.size factor = 4 size_w = int(img_w / factor) size_h = int(img_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 icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS) w = int((img_w - icon_w)/2) h = int((img_h - icon_h)/2) icon = icon.convert("RGBA") img.paste(icon, (w, h), icon) # img.show() img.save('logo-qrcode.png') make_code()