Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Python QR Code image generator

License

NotificationsYou must be signed in to change notification settings

lincolnloop/python-qrcode

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]"

What is a QR Code?

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)

Usage

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")

Advanced Usage

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 theqrcodepackage:

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).

Other image factories

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_factorykeyword argument is a valid option for theQRCode class for more advancedusage.

SVG

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')

Pure Python PNG

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)

Styled Image

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_drawerparameter 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:

doc/module_drawers.png

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_maskparameter 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:

doc/color_masks.png

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")

Examples

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

Stars

Watchers

Forks

Packages

No packages published

Contributors57

Languages


[8]ページ先頭

©2009-2025 Movatter.jp