一、生成普通二维码
简单用法
import qrcode
img = qrcode.make('hello, qrcode')
img.save('test.png')
高级用法
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data('hello, qrcode')
qr.make(fit=True)
img = qr.make_image()
img.save('123.png')
二、生成带logo二维码
import qrcode
from PIL import Image
def create_qrcode(url, filename):
qr = qrcode.QRCode(
version=1,
#设置容错率为最高
error_correction=qrcode.ERROR_CORRECT_H,
box_size=10,
border=1,
)
qr.add_data(url)
qr.make(fit=True)
img = qr.make_image()
#设置二维码为彩色
img = img.convert("RGBA")
icon = Image.open('D:/python/logo.png')
w, h = img.size
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
icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
w = int((w - icon_w) / 2)
h = int((h - icon_h) / 2)
icon = icon.convert("RGBA")
newimg = Image.new("RGBA", (icon_w + 8, icon_h + 8), (255, 255, 255))
img.paste(newimg, (w-4, h-4), newimg)
img.paste(icon, (w, h), icon)
img.save('D:/python/' + filename + '.png', quality=100)