簡單的記錄下二維碼生成和解析的Python代碼
依賴下面三個包:
- PIL(圖像處理包,安裝:
pip install PIL
) - qrcode(二維碼生成包,安裝:
pip install qrcode
) - zbarlight(二維碼解析包,安裝:
pip install zbarlight
)
具體腳本:
# coding: utf-8
"""
filename: qrcode.py
Created by Tacey Wong at 16-9-22 下午10:34
"""
import zbar
import qrcode
from PIL import Image
import os, sys
def gen_qrcode(string, path, logo=""):
"""
生成中間帶logo的二維碼
需要安裝qrcode, PIL庫
@參數 string: 二維碼字符串
@參數 path: 生成的二維碼保存路徑
@參數 logo: logo文件路徑
@return: None
"""
qr = qrcode.QRCode(
version=2,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=8,
border=1
)
qr.add_data(string)
qr.make(fit=True)
img = qr.make_image()
img = img.convert("RGBA")
if logo and os.path.exists(logo):
try:
icon = Image.open(logo)
img_w, img_h = img.size
except Exception, e:
print e
sys.exit(1)
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
icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
w = int((img_w - icon_w) / 2)
h = int((img_h - icon_h) / 2)
icon = icon.convert("RGBA")
img.paste(icon, (w, h), icon)
img.save(path)
# 調用系統命令打開圖片
# xdg - open(opens a file or URL in the user's preferred application)
os.system('xdg-open %s' % path)
def decode_qrcode(path):
"""
解析二維碼信息
@參數 path: 二維碼圖片路徑
@return: 二維碼信息
"""
# 創建圖片掃描對象
scanner = zbar.ImageScanner()
# 設置對象屬性
scanner.parse_config('enable')
# 打開含有二維碼的圖片
img = Image.open(path).convert('L')
# 獲取圖片的尺寸
width, height = img.size
# 建立zbar圖片對象並掃描轉換為字節信息
qrCode = zbar.Image(width, height, 'Y800', img.tobytes())
scanner.scan(qrCode)
# 組裝解碼信息
data = ''
for s in qrCode:
data += s.data
# 刪除圖片對象
del img
# 輸出解碼結果
return data
if __name__ == "__main__":
info = "中華人民共和國合法公民——Tacey Wong\nhttp://www.cnblogs.com/taceywong"
pic_path = "qr.png"
icon_path = "logo.png"
gen_qrcode(info, pic_path,logo_path )
print decode_qrcode(pic_path)
生成的二維碼圖片如下:
掃描結果如下: