Python二維碼生成庫qrcode示例

jopen 8年前發布 | 46K 次閱讀 條形碼/二維碼開發包

二維碼簡稱 QR Code(Quick Response Code),學名為快速響應矩陣碼,是二維條碼的一種,由日本的 Denso Wave 公司于 1994 年發明。現隨著智能手機的普及,已廣泛應用于平常生活中,例如商品信息查詢、社交好友互動、網絡地址訪問等等。

由于生成 qrcode 圖片需要依賴 Python 的圖像庫,所以需要先安裝 Python 圖像庫 PIL(Python Imaging Library),不然會遇到 ImportError: No module named Image的錯誤。

PNG

From the command line, use the installed qr script:

qr "Some text" > test.png

Example:

import qrcode

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('http://zzir.cn/')
qr.make(fit=True)
img = qr.make_image()
img.save("qrcode_demo.png")

參數 version 表示生成二維碼的尺寸大小,取值范圍是 140,最小尺寸 1 會生成 21 * 21 的二維碼,version 每增加 1,生成的二維碼就會添加 4 尺寸,例如 version2,則生成 25 * 25 的二維碼。

參數 error_correction 指定二維碼的容錯系數,分別有以下4個系數:

  1. ERROR_CORRECT_L: 7%的字碼可被容錯

  2. ERROR_CORRECT_M: 15%的字碼可被容錯

  3. ERROR_CORRECT_Q: 25%的字碼可被容錯

  4. ERROR_CORRECT_H: 30%的字碼可被容錯

參數 box_size 表示二維碼里每個格子的像素大小。

參數 border 表示邊框的格子厚度是多少(默認是4)。

SVG

On Python 2.6 must install lxml since the older xml.etree.ElementTree version can not be used to create SVG images.

You can create the entire SVG or an SVG fragment. When building an entire SVG image, you can use the factory that combines as a path (recommended, and default for the script) or a factory that creates a simple set of rectangles.

From your command line:

qr --factory=svg-path "Some text" > test.svg
qr --factory=svg "Some text" > test.svg
qr --factory=svg-fragment "Some text" > test.svg

Or in Python:

import qrcode
import qrcode.image.svg

if method == 'basic':
    # Simple factory, just a set of rects.
    factory = qrcode.image.svg.SvgImage
elif method == 'fragment':
    # Fragment factory (also just a set of rects)
    factory = qrcode.image.svg.SvgFragmentImage
else:
    # Combined path factory, fixes white space that may occur when zooming
    factory = qrcode.image.svg.SvgPathImage

img = qrcode.make('Some data here', image_factory=factory)

Two other related factories are available that work the same, but also fill the background of the SVG with white:

qrcode.image.svg.SvgFillImage
qrcode.image.svg.SvgPathFillImage

Pure Python PNG

Install the following two packages:

pip install git+git://github.com/ojii/pymaging.git#egg=pymaging
pip install git+git://github.com/ojii/pymaging-png.git#egg=pymaging-png

From your command line:

qr --factory=pymaging "Some text" > test.png

Or in Python:

import qrcode
from qrcode.image.pure import PymagingImage
img = qrcode.make('Some data here', image_factory=PymagingImage)

參考:https://pypi.python.org/pypi/qrcode/5.1

來自: https://segmentfault.com/a/1190000004318017

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!