Python之QRCode

星空28發表於2024-08-24

方法一:

生成二維碼

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')

相關文章