Python利用qrcode生成二维码并解析结果
生活随笔
收集整理的這篇文章主要介紹了
Python利用qrcode生成二维码并解析结果
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用到的庫(kù)
1、qrcode
介紹:qrcode模塊是Github上的一個(gè)開源項(xiàng)目,提供了生成二維碼的接口。qrcode模塊默認(rèn)使用PIL庫(kù)用于生成圖像。
安裝:
使用到的函數(shù):qrcode.QRCode(),該函數(shù)用于生成二維碼,傳入的參數(shù)為生成二維碼的內(nèi)容以及樣式控制
2、pyzbar
介紹:pyzbar是python的一個(gè)第三方庫(kù),其作用包括條形碼生成和掃描器。
安裝:
使用到的函數(shù):pyzbar.decode(),該函數(shù)用于解析二維碼存儲(chǔ)的信息
3、PIL
介紹:PIL,全稱Python Image Library,主要作用是圖像處理,可用于圖片剪切、粘貼、縮放、鏡像、水印、顏色塊、濾鏡、圖像格式轉(zhuǎn)換、色場(chǎng)空間轉(zhuǎn)換、驗(yàn)證碼、旋轉(zhuǎn)圖像、圖像增強(qiáng)、直方圖處理、插值和濾波等功能
安裝:
代碼
# -*- coding:utf-8 -*- import os import qrcode from PIL import Image from pyzbar import pyzbardef make_qr_code_with_icon(content, icon_path, save_path=None):if not os.path.exists(icon_path):raise FileExistsError(icon_path)# First, generate an usual QR Code imageqr_code_maker = qrcode.QRCode(version=5,error_correction=qrcode.constants.ERROR_CORRECT_H,box_size=8,border=4,)qr_code_maker.add_data(data=content)qr_code_maker.make(fit=True)qr_code_img = qr_code_maker.make_image(fill_color="black", back_color="white").convert('RGBA')# Second, load icon image and resize iticon_img = Image.open(icon_path)code_width, code_height = qr_code_img.sizeicon_img = icon_img.resize((code_width // 4, code_height // 4), Image.ANTIALIAS)# Last, add the icon to original QR Codeqr_code_img.paste(icon_img, (code_width * 3 // 8, code_width * 3 // 8))if save_path:qr_code_img.save(save_path) # 保存二維碼圖片qr_code_img.show() # 顯示二維碼圖片else:print("保存錯(cuò)誤!")def decode_qr_code(code_img_path):if not os.path.exists(code_img_path):raise FileExistsError(code_img_path)# Here, set only recognize QR Code and ignore other type of codereturn pyzbar.decode(Image.open(code_img_path), symbols=[pyzbar.ZBarSymbol.QRCODE])if __name__ == "__main__":print("1、請(qǐng)輸入編碼信息(可以為文字、鏈接、圖片地址):")code_Data = input('>>:').strip()print("正在編碼:")# ==生成帶中心圖片的二維碼make_qr_code_with_icon(code_Data, "QRcodeCenter.jpg", "qrcode.png") # 內(nèi)容,center圖片,生成二維碼圖片print("圖片已保存,名稱為:qrcode.png")results = decode_qr_code("qrcode.png")print("2、正在解碼:")if len(results):print("解碼結(jié)果是:")res = results[0].data.decode("utf-8")print(res)with open(r"./info.txt", "a+", encoding='utf-8')as f:f.seek(0)f.truncate()f.write(res)else:print("無法識(shí)別.")總結(jié)
以上是生活随笔為你收集整理的Python利用qrcode生成二维码并解析结果的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux系统命令行执行MySQL脚本
- 下一篇: 进程间通信——消息队列(Message