python批量生成帶logo帶文字的二維碼
阿新 • • 發佈:2022-04-10
1. 核心檔案(01.py), 所有的主要邏輯都在這裡面
from PIL import ImageFont, ImageDraw, Image import qrcode import os def createQrCode(text): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, # 比例大約等於1:28 box_size=20, border=1, ) qr.add_data(text) qr.make(fit=True) qrImg = qr.make_image(fill_color="black", back_color="white") return qrImg def createBg(qrImg): img = qrImg.resize((580, 580), Image.ANTIALIAS) bg = Image.new("RGB", (580, 660), "#ffffff") bg.paste(img, (0, 0)) return bg def drawFont(bg, text): fontStyle = "./文泉驛等寬微米黑.ttf" font = ImageFont.truetype(fontStyle, 24) w, h = font.getsize(text) # 70, 15 draw = ImageDraw.Draw(bg) draw.text(((580 - w) / 2, 600), text, fill="#000000", font=font) return bg def drawLogo(qr, logo, proportion): w, h = qr.size logo = Image.open(logo) resizeW = (int(w * proportion))# resizeW = type(size) logo = logo.resize((resizeW, resizeW), Image.ANTIALIAS) logoW, logoH = logo.size center = int((w - logoW) / 2) qr.paste(logo, (center, center)) return qr def draw(qrText, descText, logoPath, savePath, filename, proportion): qrImg = createQrCode(qrText) bgImg = createBg(qrImg) bgImg2 = drawFont(bgImg, descText) res = drawLogo(bgImg2, logoPath, proportion) # 判斷是否有對應的資料夾, 沒有的話, 手動生成一個 if (savePath in os.listdir() and os.path.isfile(savePath) or savePath not in os.listdir()): os.mkdir(savePath) res.save(os.path.join(savePath, filename)) print(f"生成二維碼『{filename}』成功") """ 引數說明: draw(qrText, descText, logoPath, savePath, filename, proportion) qrText: 二維碼顯示的內容 descText: 二維碼下面的文案顯示 logoPath: 二維碼中間的logo路徑, 相對/絕對 savePath: 儲存的資料夾路徑, 例如 ./ (當前) filename: 希望儲存的名字 proportion: logo 相對於 二維碼的比例 """ # 單獨生成一張 # draw("2021101023", "2021101023", "./logo.jpg", "temp", "02.png", 0.25) # 讀取檔案, 生成若干張 def readProperties(path): with open(path, 'r', encoding="utf-8") as file: qrList = file.readlines() for i in qrList: cfg = i.strip().split('|') if (len(cfg) == 6): draw(cfg[0], cfg[1], cfg[2], cfg[3], cfg[4], float(cfg[5])) readProperties('./qrcode.txt')
2. 目錄檔案(qrcode.txt), 如圖所示, 會成成六張二維碼
2021101023|2021101023|logo.jpg|電客二維碼|02.png|0.25 2021101024|2021101024|logo.jpg|電客二維碼|23.png|0.25 2021101025|2021101025|logo.jpg|電客二維碼|24.png|0.25 2021101026|2021101026|logo.jpg|電客二維碼|25.png|0.25 2021101027|2021101027|logo.jpg|電客二維碼|26.png|0.25 2021101028|2021101028|logo.jpg|電客二維碼|27.png|0.25 2021101029|2021101029|logo.jpg|電客二維碼|28.png|0.25 2021101034|2021101034|logo.jpg|電客二維碼|29.png|0.25
3. 執行檔案 ( generate.bat ), 沒有的話, 直接執行 01.py 也是一樣的
python 01.py
pause
4. 其他檔案(自備)
logo檔案
ttf字型檔案
結果展示