Python implements an example of a method that generates a QR code from text
- 2020-06-12 09:47:27
- OfStack
This article gives an example of an Python implementation that generates 2-dimensional code from text. To share for your reference, specific as follows:
#coding:utf-8
'''
Python generate 2 D code v1.0
Basically generate the text 2 D code pictures
test 1 : Creates black text on a white background 2 D code pictures
test 2 : Generates a text band logo the 2 D code pictures
'''
__author__ = 'Xue'
import qrcode
from PIL import Image
import os
# generate 2 D code pictures
def make_qr(str,save):
qr=qrcode.QRCode(
version=4, # generate 2 The size of a dimension 1-40 1:21*21 ( 21+(n-1)*4 )
error_correction=qrcode.constants.ERROR_CORRECT_M, #L:7% M:15% Q:25% H:30%
box_size=10, # The pixel size of each cell
border=2, # The grid width size of the border
)
qr.add_data(str)
qr.make(fit=True)
img=qr.make_image()
img.save(save)
# Generated with logo the 2 D code pictures
def make_logo_qr(str,logo,save):
# Parameter configuration
qr=qrcode.QRCode(
version=4,
error_correction=qrcode.constants.ERROR_CORRECT_Q,
box_size=8,
border=2
)
# Add conversion content
qr.add_data(str)
#
qr.make(fit=True)
# generate 2 D code
img=qr.make_image()
#
img=img.convert("RGBA")
# add logo
if logo and os.path.exists(logo):
icon=Image.open(logo)
# To obtain 2 The size of a dimensional image
img_w,img_h=img.size
factor=4
size_w=int(img_w/factor)
size_h=int(img_h/factor)
#logo The size of the picture must not exceed 2 Dimension code picture 1/4
icon_w,icon_h=icon.size
if icon_w>size_w:
icon_w=size_w
if icon_h>size_h:
icon_h=size_h
icon=icon.resize((icon_w,icon_h),Image.ANTIALIAS)
# To calculate logo in 2 The position in a dimension chart
w=int((img_w-icon_w)/2)
h=int((img_h-icon_h)/2)
icon=icon.convert("RGBA")
img.paste(icon,(w,h),icon)
# Save the processed image
img.save(save)
if __name__=='__main__':
save_path='theqrcode.png' # The generated save file
logo='logo.jpg' #logo The picture
str=raw_input(' Please enter to generate 2 Text content of dimension code: ')
#make_qr(str)
make_logo_qr(str,logo,save_path)
PS: Here is another recommended 2-d code online generation tool for your reference:
Online 2-d code Generation tool (Enhanced)
http://tools.ofstack.com/transcoding/jb51qrcode
For more information about Python, please refer to Python Coding Skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Using Skills Summary, Python String Operation Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Operation Skills Summary.
I hope this article is helpful for Python programming.