A QR code generator builds QRcode for any data, website, etc in Python. The QR Code can be even placed over an image or can be customized using qrcode module in python.
The QR Code generator is simple to implement and can be made dynamic. This packet uses os, pillow, qrcode modules of Python. Pillow is used in formatting the image to make it suitable for fitting with the QR code image. This packet saves the QR code in '.png' format.
Formatting parameters for code:
# Setting version,border,error_correction and advanced parameters for qrcode # You can adjust the size and version qr_code = qrcode.QRCode( version=2, # Using ERROR_CORRECT_L for high correction error_correction=qrcode.constants.ERROR_CORRECT_L, box_size = 3, border=2 )
The above packet stores the parameter like error_correction, border, box_size, version for the code. Error_correction used is ERROR_CORRECT_L that corrects about 7% or fewer errors. Box_size defines the size of the QR code and the border defines the size of the bounding code border.
# Input the data to be present in the qrcode code_data = str(input("Enter the data(i.e. link,code etc): ")) # Adding data into qrcode qr_code.add_data(code_data) qr_code.make(fit=True) qrcode_path = os.path.dirname(os.path.abspath(__file__)) # Enter the name of file for qrcode file_name = str(input("Enter the name for image: "))
The above piece of code takes an input of data to be stored in the QR code in form of a string. The data can be a link or any other data. The data is fitted using the '.fit ' function. The other input function takes the name of the file as input with which the QR code image is being saved.
Creating and saving QR code:
# Generating qrcode in image(.png) format and saving img = qr_code.make_image(fill_color="black",back_color="white") img.save(os.path.join(qrcode_path,file_name+".png"))
This packet generates QR code in image form and saves it in '.png' format
Placing QR code on image:
Also the QR code can be pasted on any image using the following code:
# For inserting the qrcode on the image # # Opening Image to insert in qrcode # img_ref = Image.open("Put the path of the image on which the QR code is to be pasted") # # Making the coordinates for qrcode on image # position = ((img_ref.size-img.size),(img_ref.size-img.size)) # # Pasting qrcode on image and saving # img_ref.paste(img,position) # img_ref.save(os.path.join(qrcode_path,file_name+".png"))
This code needs to be complemented out to be able to use it. Put the path of the image on which the QR code is to be integrated into the labeled region. Position variable stores the points for placing the QR code on the image. Further code-block places the QR code on the image and saves it in '.png' format.
Submitted by Rachit R Jindal (rachit99)
Download packets of source code on Coders Packet