天天看點

PyQt5實戰之二維碼生成器(三):定制化二維碼

前言

經過上一章,我們實作界面中各個控件的功能,本章将說明二維碼的生成及樣式修改。

千呼萬喚始出來(雖然并沒有呼喚,但總要想個開頭),終于到了核心功能的生成二維碼部分。萬能的Python生态中自然不乏生成二維碼的庫,筆者采用的是以下兩個庫,分别用于生成 logo 和背景圖模式的二維碼。

import qrcode
from MyQR import myqr
           

文章目錄

    • 一、自定義前景色和Logo
    • 二、自定義背景圖
    • 三、在 getQR() 中使用
    • 四、本章小結

一、自定義前景色和Logo

輸入的參數為:資料、尺寸(預設為5,暫未增加使用者修改的功能)、圖像路徑(預設無圖像,可以修改前景色)、顔色代碼(預設黑色)。

def QR_qrcode(data, size=5, imagepath=None, color='#000000'):
    try:
        qr = qrcode.QRCode(
            version = 4, # 精度,預設6
            error_correction = qrcode.constants.ERROR_CORRECT_H,
            box_size = size, # 尺寸,預設5
            border = 3 )
        qr.add_data(data)
        qr.make(fit=True)

        img = qr.make_image(fill_color = color)
        img = img.convert('RGBA') # 設為彩色

        if imagepath != None: # 如果打開了圖檔
            logo = Image.open(imagepath)  # 二維碼中心的圖檔
            img_w, img_h = img.size     # 二維碼尺寸由box_size參數設定
            # logo_w, logo_h = logo.size  # logo圖檔尺寸
            logo_w = int(img_w/4)
            logo_h = int(img_h/4)
            logo = logo.resize((logo_w, logo_h), Image.ANTIALIAS)
            w = int((img_w - logo_w) / 2) # logo在二維碼中的位置
            h = int((img_h - logo_h) / 2)
            logo = logo.convert('RGBA')
            img.paste(logo, (w, h), logo)

        img.save('test_qr.png')
    except:
        pass
           

二、自定義背景圖

輸入的參數為:資料、圖像路徑、檔案名(根據使用者選擇靜态圖和動态圖而有所不同)、尺寸(精度)、透明度(通過對比度和亮度兩個參數共同實作透明度的調節)。

def QR_myqr(data, imagepath, filename, size=8, contrast=1.0): 
    try:
        print("------\nbackground-image path:",imagepath)
        myqr.run(
            words = data,
            version = size, # 大小1~40,預設8
            level='H', # 糾錯級别
            picture = imagepath, # 底圖
            colorized = True, # 彩色
            contrast = contrast, # 對比度
            brightness = 1.0 + (1-contrast), # 亮度
            save_name = filename,
            save_dir = os.getcwd() #目前目錄
        )
        print('get version_back')
    except:
        print('warning: background error')
           

三、在 getQR() 中使用

還記得在資料輸入章節中的

getQR()

方法嗎?接下來需要将生成二維碼的方法按需求整合進去。

def getQR(self): # 生成二維碼
    data_flag = self.toolBox.currentIndex() # 資料類型(所選欄目)
    data = ''
    . . . . . .
    # 執行生成二維碼 ------
    try:
        pass
    except:
        pass
           

來看一下在

try

中需要寫入的代碼,首先是帶圖檔的 logo 模式,調用

QR_qrcode()

方法傳入資料、圖像路徑和顔色代碼。

if self.radioButton_0.isChecked() and imagepath != '':  # 選擇logo且打開了圖檔
    QR_qrcode(data, imagepath=imagepath, color=color)
           
PyQt5實戰之二維碼生成器(三):定制化二維碼

然後是帶圖檔的背景圖模式,調用

QR_myqr()

方法傳入資料、圖像路徑、檔案名。如果使用者選擇動态圖作為底圖,需縮小圖像尺寸,且不可修改透明度,并彈出提示告知使用者需在根目錄檢視生成的動态二維碼;如果使用者選擇靜态圖,則可以修改透明度。

elif self.radioButton_1.isChecked() and imagepath != '':  # 選擇background且打開了圖檔
    if filetype == ".gif":
        QMessageBox.about(self,self.tr("Remind"),self.tr("Detected as GIF image, please wait...\n(*Note: transparency cannot be modified)"))
        QR_myqr(data, path,'test_qr.gif',size = 3)  # gif底圖縮小尺寸,限制透明度不變
        QMessageBox.about(self, self.tr("Remind"), self.tr("Please check the generated GIF in the root directory !"))
    else:
        QR_myqr(data, path, 'test_qr.png', contrast =depth)
           
PyQt5實戰之二維碼生成器(三):定制化二維碼

接着是無圖像二維碼,調用

QR_qrcode()

方法傳入資料和顔色代碼即可。

elif imagepath == '':  # 無圖
    QR_qrcode(data, color=color)
           

最後讀入生成的圖像,将其在 label 中顯示出來即可。至此,便已實作自定義二維碼生成器的基本功能。

file = 'test_qr.png' if filetype != ".gif" else 'test_qr.gif'
img = QPixmap(file).scaled(self.label_result.width(), self.label_result.height())  # 裁剪圖檔
self.label_result.setPixmap(img)  # 加載圖檔
           
PyQt5實戰之二維碼生成器(三):定制化二維碼

四、本章小結

第三章我們利用 qrcode 和 MyQR 庫實作了定制化二維碼的生成,可以修改二維碼的顔色、logo、背景圖等。關于二維碼的定制化還有更多方式,有機會可以再進行探究。下一章将繼續講解界面的國際化、管理打包資源兩個部分的内容,敬請關注!