天天看點

Python——生成二維碼1 使用 MyQR 生成二維碼2 使用 qrcode 生成二維碼

1 使用 MyQR 生成二維碼

先安裝 myqr,使用 cmd 指令:

pip install myqr

如果安裝失敗,可以嘗試使用管理者身份啟動 cmd,再次安裝試試

python 代碼為:

from MyQR import myqr;
myqr.run(words="https://www.baidu.com", picture="test.png", colorized=True, save_name="my.png");

           

words str 為掃描後跳轉的連結,也可以為要顯示的字元串

picture 為二維碼上的圖檔,可以自定義自己的圖檔

colorized 為 True 時,可以顯示為彩色圖檔

save_name 為生成的二維碼圖檔名,預設檔案名是"qrcode.png"

當 picture 為 gif 格式時,設定 save_name 也同樣為 gif,此時二維碼為動态二維碼

其他參數:

save_dir 存儲位置 str,預設存儲位置是目前目錄

version 邊長 int,控制邊長,範圍是1到40,數字越大邊長越大,預設邊長是取決于你輸入的資訊的長度和使用的糾錯等級

level 糾錯等級 str,控制糾錯水準,範圍是L、M、Q、H,從左到右依次升高,預設糾錯等級為’H’

contrast 對比度 float,調節圖檔的對比度,1.0 表示原始圖檔,更小的值表示更低對比度,更大反之。預設為1.0

brightness 亮度 float,調節圖檔的亮度,其餘用法和取值與 contrast 相同

Python——生成二維碼1 使用 MyQR 生成二維碼2 使用 qrcode 生成二維碼

2 使用 qrcode 生成二維碼

下載下傳 qrcode 包和依賴的 Image 包:

pip install qrcode
pip install Image
           
Python——生成二維碼1 使用 MyQR 生成二維碼2 使用 qrcode 生成二維碼

python 代碼:

# 用 qrcode 生成二維碼
## 例子1,簡單生成二維碼
import qrcode
img = qrcode.make('https://www.baidu.com')
with open('test.png', 'wb') as f:
img.save(f)


## 例子2 一般步驟生成預設二維碼
import qrcode

data = 'http://www.baidu.com/'
img_file = 'dir/test.png'

 # 執行個體化QRCode生成qr對象
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_H,
    box_size=10,
    border=4
 )
 # 傳入資料
 qr.add_data(data)

 qr.make(fit=True)

 # 生成二維碼
 img = qr.make_image()

 # 儲存二維碼
 img.save(img_file)
 # 展示二維碼
 img.show()

## 例子3, 添加自定義圖檔和内容
import qrcode
from PIL import Image
import matplotlib.pyplot as plt


def getQRcode(data, file_name):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=5,
        border=4,
    )

    # 添加資料
    qr.add_data(data)
    # 填充資料
    qr.make(fit=True)
    # 生成圖檔
    img = qr.make_image(fill_color="green", back_color="white")

    # 添加logo,打開logo照片,該圖檔為要放在二維碼中顯示的自定義圖檔,dir 為圖檔目錄
    icon = Image.open("dir/timg[1].png")
    # 擷取圖檔的寬高
    img_w, img_h = img.size
    # 參數設定logo的大小
    factor = 6
    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.ANTIALIAS)
    # 得到畫圖的x,y坐标,居中顯示
    w = int((img_w - icon_w) / 2)
    h = int((img_h - icon_h) / 2)
    # 黏貼logo照
    img.paste(icon, (w, h), mask=None)
    # 終端顯示圖檔
    plt.imshow(img)
    plt.show()
    # 儲存img
    img.save(file_name)
    return img

# “你好”為自定義内容, 生成二維碼為 my.png
if __name__ == '__main__':
    getQRcode("你好", 'my.png')
           

使用 qrcode 生成二維碼的一般步驟為:

建立QRCode對象

add_data()添加資料

make_image()建立二維碼(傳回im類型的圖檔對象)

自動打開圖檔,im.show()