- Notifications
You must be signed in to change notification settings - Fork719
Python QR Code image generator
License
lincolnloop/python-qrcode
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Generate QR codes.
A standard install usespypng to generate PNG files and can also render QRcodes directly to the console. A standard install is just:
pip install qrcode
For more image functionality, install qrcode with thepil
dependency sothatpillow is installed and can be used for generating images:
pip install "qrcode[pil]"
A Quick Response code is a two-dimensional pictographic code used for its fastreadability and comparatively large storage capacity. The code consists ofblack modules arranged in a square pattern on a white background. Theinformation encoded can be made up of any kind of data (e.g., binary,alphanumeric, or Kanji symbols)
From the command line, use the installedqr
script:
qr "Some text" > test.png
Or in Python, use themake
shortcut function:
importqrcodeimg=qrcode.make('Some data here')type(img)# qrcode.image.pil.PilImageimg.save("some_file.png")
For more control, use theQRCode
class. For example:
importqrcodeqr=qrcode.QRCode(version=1,error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=10,border=4,)qr.add_data('Some data')qr.make(fit=True)img=qr.make_image(fill_color="black",back_color="white")
Theversion
parameter is an integer from 1 to 40 that controls the size ofthe QR Code (the smallest, version 1, is a 21x21 matrix).Set toNone
and use thefit
parameter when making the code to determinethis automatically.
fill_color
andback_color
can change the background and the paintingcolor of the QR, when using the default image factory. Both parameters acceptRGB color tuples.
img=qr.make_image(back_color=(255,195,235),fill_color=(55,95,35))
Theerror_correction
parameter controls the error correction used for theQR Code. The following four constants are made available on theqrcode
package:
ERROR_CORRECT_L
- About 7% or less errors can be corrected.
ERROR_CORRECT_M
(default)- About 15% or less errors can be corrected.
ERROR_CORRECT_Q
- About 25% or less errors can be corrected.
ERROR_CORRECT_H
.- About 30% or less errors can be corrected.
Thebox_size
parameter controls how many pixels each "box" of the QR codeis.
Theborder
parameter controls how many boxes thick the border should be(the default is 4, which is the minimum according to the specs).
You can encode as SVG, or use a new pure Python image processor to encode toPNG images.
The Python examples below use themake
shortcut. The sameimage_factory
keyword argument is a valid option for theQRCode
class for more advancedusage.
You can create the entire SVG or an SVG fragment. When building an entire SVGimage, you can use the factory that combines as a path (recommended, anddefault for the script) or a factory that creates a simple set of rectangles.
From your command line:
qr --factory=svg-path "Some text" > test.svgqr --factory=svg "Some text" > test.svgqr --factory=svg-fragment "Some text" > test.svg
Or in Python:
importqrcodeimportqrcode.image.svgifmethod=='basic':# Simple factory, just a set of rects.factory=qrcode.image.svg.SvgImageelifmethod=='fragment':# Fragment factory (also just a set of rects)factory=qrcode.image.svg.SvgFragmentImageelse:# Combined path factory, fixes white space that may occur when zoomingfactory=qrcode.image.svg.SvgPathImageimg=qrcode.make('Some data here',image_factory=factory)
Two other related factories are available that work the same, but also fill thebackground of the SVG with white:
qrcode.image.svg.SvgFillImageqrcode.image.svg.SvgPathFillImage
TheQRCode.make_image()
method forwards additional keyword arguments to theunderlying ElementTree XML library. This helps to fine tune the root element ofthe resulting SVG:
importqrcodeqr=qrcode.QRCode(image_factory=qrcode.image.svg.SvgPathImage)qr.add_data('Some data')qr.make(fit=True)img=qr.make_image(attrib={'class':'some-css-class'})
You can convert the SVG image into strings using theto_string()
method.Additional keyword arguments are forwarded to ElementTreestostring()
:
img.to_string(encoding='unicode')
If Pillow is not installed, the default image factory will be a pure Python PNGencoder that uses pypng.
You can use the factory explicitly from your command line:
qr --factory=png "Some text" > test.png
Or in Python:
importqrcodefromqrcode.image.pureimportPyPNGImageimg=qrcode.make('Some data here',image_factory=PyPNGImage)
Works only withversions >=7.2 (SVG styled images require 7.4).
To apply styles to the QRCode, use theStyledPilImage
or one of thestandardSVG image factories. These accept an optionalmodule_drawer
parameter to control the shape of the QR Code.
These QR Codes are not guaranteed to work with all readers, so do someexperimentation and set the error correction to high (especially if embeddingan image).
Other PIL module drawers:
For SVGs, useSvgSquareDrawer
,SvgCircleDrawer
,SvgPathSquareDrawer
, orSvgPathCircleDrawer
.
These all accept asize_ratio
argument which allows for "gapped" squares orcircles by reducing this less than the default ofDecimal(1)
.
TheStyledPilImage
additionally accepts an optionalcolor_mask
parameter to change the colors of the QR Code, and an optionalembedded_image_path
to embed an image in the center of the code.
Other color masks:
Here is a code example to draw a QR code with rounded corners, radial gradientand an embedded image:
importqrcodefromqrcode.image.styledpilimportStyledPilImagefromqrcode.image.styles.moduledrawers.pilimportRoundedModuleDrawerfromqrcode.image.styles.colormasksimportRadialGradiantColorMaskqr=qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)qr.add_data('Some data')img_1=qr.make_image(image_factory=StyledPilImage,module_drawer=RoundedModuleDrawer())img_2=qr.make_image(image_factory=StyledPilImage,color_mask=RadialGradiantColorMask())img_3=qr.make_image(image_factory=StyledPilImage,embedded_image_path="/path/to/image.png")
Get the text content from print_ascii:
importioimportqrcodeqr=qrcode.QRCode()qr.add_data("Some text")f=io.StringIO()qr.print_ascii(out=f)f.seek(0)print(f.read())
The add_data method will append data to the current QR object. To add new data by replacing previous content in the same object, first use clear method:
importqrcodeqr=qrcode.QRCode()qr.add_data('Some data')img=qr.make_image()qr.clear()qr.add_data('New data')other_img=qr.make_image()
Pipe ascii output to text file in command line:
qr --ascii "Some data" > "test.txt"cat test.txt
Alternative to piping output to file to avoid PowerShell issues:
# qr "Some data" > test.pngqr --output=test.png "Some data"
About
Python QR Code image generator
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.