26 November, 2023
0 Comments
PythonのQRコード画像生成ライブラリ「qrcode」
pip install qrcode
QRコードの中に画像を埋め込む
- download lena.png
- create QR code with string: “I am Lena”
- add mini image overlay of QR code.
- save to new image: qr_lena2.png
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ref: https://note.nkmk.me/python-pillow-qrcode/
# pip install qrcode
# wget http://optipng.sourceforge.net/pngtech/img/lena.png
import qrcode
from PIL import Image
import requests
import os
def dw_img(fimg='lena.png', img_url=None):
print("download image:", fimg)
if img_url is None:
image_url = 'http://optipng.sourceforge.net/pngtech/img/lena.png'
img_data = requests.get(image_url).content
with open(fimg, 'wb') as handler:
handler.write(img_data)
# ----------draw image overlay------------------------------------------------------
fimg = "lena.png"
if not os.path.exists(fimg):
print("down load file:", fimg)
dw_img()
# face image for overlay
img = Image.open('lena.png')
face = img.crop((218, 219, 373, 374)).resize((60, 60), Image.LANCZOS)
qr_big = qrcode.QRCode(
error_correction=qrcode.constants.ERROR_CORRECT_H
)
qr_big.add_data('I am Lena')
qr_big.make()
# convert qr code to RGB image.
img_qr_big = qr_big.make_image().convert('RGB')
pos = ((img_qr_big.size[0] - face.size[0]) // 2,
(img_qr_big.size[1] - face.size[1]) // 2)
img_qr_big.paste(face, pos)
img_qr_big.save('qr_lena2.png')
Category: tech