- 使用qrcode生成二维码,安装qrcode
pip install qrcode
- 生成二维码,并保存图片
import qrcode
# 创建QRCode对象
qr = qrcode.QRCode(
version=40,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=10,
border=4,
)
# data为要生成的二维码文本
qr.add_data(data.encode('utf-8'))
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save("qr_code.png")
- 使用pyzbar,安装pyzbar
pip install pyzbar
- 二维码解析
from pyzbar import pyzbar
result = pyzbar.decode(Image.open('qr_code.png'))
有些中文,解析出来可能是乱码,这里我使用了base64对字符串进行加密,二维码识别解析之后再通过base64解密
base64文本加密
import base64
txt_data = base64.b64encode("文本内容".encode('utf-8')).decode("utf-8")
print(txt_data)
base64文本解密
# txt_data base64加密后密文
txt = base64.b64decode(txt_data).decode("utf-8")
完整代码
import qrcode
import base64
from PIL import Image
from pyzbar import pyzbar
def make_qrcode(data):
# 创建QRCode对象
qr = qrcode.QRCode(
version=40,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=10,
border=4,
)
# data为要生成的二维码文本
qr.add_data(data.encode('utf-8'))
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save("qr_code_image.png")
encode_txt = base64.b64encode("文本加密长文本长文本".encode('utf-8')).decode("utf-8")
make_qrcode(encode_txt)
result = pyzbar.decode(Image.open('qr_code_image.png'))
#获取解析内容
decode_qr_txt = result[0].data.decode('utf-8')
decode = base64.b64decode(decode_qr_txt).decode("utf-8")
print(decode)
注意:如果是长文本的二维码生成与解析,需要在设置生成二维码的文本长度控制为4的倍数
即:上边代码块的 encode_txt 需要切割为4的倍数,由于已经转为base64格式,我默认设置长度为2000(仅供参考)