Install what you need to run on colab.
Installation of required libraries
pip install qrcode pillow
Install the font to write the Japanese character string to the image with the prepared sample
!apt-get -y install fonts-ipafont-gothic
import qrcode
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
imgpath = "qr.png " #Image storage location and file name
text = "Return" #Information you want to incorporate into the QR code
#This time I want to add Japanese notation, so I prepared a Japanese font
fontname = "/usr/share/fonts/opentype/ipafont-gothic/ipag.ttf"
#Character size to be written
fontsize = 36
#Function to get the font size to be written
def getTextSize(_text="test", _fontname="", _fontsize=36):
canvasSize = (1, 1)
backgroundRGB = (255, 255, 255)
img = PIL.Image.new("RGB", canvasSize, backgroundRGB)
draw = PIL.ImageDraw.Draw(img)
font = PIL.ImageFont.truetype(_fontname, _fontsize)
textWidth, textHeight = draw.textsize(_text, font=font)
return textWidth, textHeight
#Create a QR code and add the character notation to the bottom center
def makeQRimg(_imgpath, _text, _fontname="", _fontsize=36):
#Maximum error correction level, margin is the minimum width in the specifications
qr = qrcode.QRCode(
error_correction=qrcode.constants.ERROR_CORRECT_H,
border=4,
)
qr.add_data(_text)
qr.make()
img = qr.make_image().convert("RGB")
textSize = getTextSize(_text, _fontname, _fontsize)
textTopLeft = (img.size[0]/2 - textSize[0]/2, img.size[1] - textSize[1])
draw = PIL.ImageDraw.Draw(img)
font = PIL.ImageFont.truetype(_fontname, _fontsize)
draw.text(xy=textTopLeft, text=_text, fill=(0, 0, 0), font=font)
#Save QR code
img.save(_imgpath)
#Run
makeQRimg(imgpath, text, fontname, fontsize)
#Display the created QR code on IPython
from IPython.display import Image, display_png
display_png(Image(imgpath))
Recommended Posts