Python之QRCode

方法一:

生成二维码

import qrcode
# 生成二维码
img = qrcode.make(data="你好")
# 将二维码保存为图片
with open('qrcode_test.png', 'wb') as f:
    img.save(f)

解码二维码


import cv2
d=cv2.QRCodeDetector()
val,_,_ = d.detectAndDecode(cv2.imread('qrcode_test.png'))   # 绝对路径也可
print('text is:',val)

方法二

import qrcode

qr = qrcode.QRCode(
    version=5,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)

qr.add_data('https://editor.csdn.net/')

qr.make(fit=True)
img = qr.make_image()
filename = 'qrcode.png'
img.save(filename)
img.show()

方法三:生成带有图片的二维码

from PIL import Image
import qrcode

qr = qrcode.QRCode(
    version=5,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('https://www.cnblogs.com/nthforsth/')
qr.make(fit=True)

img = qr.make_image()
img = img.convert("RGBA")

# 添加logo,打开logo照片
icon = Image.open(r"D:\Work\ProjectItems\Restframework_Test\DRFdemo\files\image\1721713687503.png")

  # 获取图片的宽高
img_w, img_h = img.size
# 参数设置logo的大小
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

# 重新设置logo的尺寸
icon = icon.resize((icon_w, icon_h), Image.Resampling.LANCZOS)

# 得到画图的x,y坐标,居中显示
w = int((img_w - icon_w) / 2)
h = int((img_h - icon_h) / 2)
icon = icon.convert("RGBA")

# 黏贴logo照
img.paste(icon, (w, h),icon)
img.show()
img.save('icon_qrcode.png')

posted @ 2024-08-24 12:01  星空28  阅读(106)  评论(0编辑  收藏  举报