二維碼簡稱 QR Code(Quick Response Code),學名爲快速響應矩陣碼,是二維條碼的一種,由日本的 Denso Wave 公司於 1994 年發明。現隨着智能手機的普及,已普遍應用於日常生活中,例如商品信息查詢、社交好友互動、網絡地址訪問等等。python
因爲生成 qrcode 圖片須要依賴 Python 的圖像庫,因此須要先安裝 Python 圖像庫 PIL(Python Imaging Library),否則會遇到 ImportError: No module named Image
的錯誤。git
From the command line, use the installed qr script:github
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
表示生成二維碼的尺寸大小,取值範圍是 1
至 40
,最小尺寸 1
會生成 21 * 21
的二維碼,version
每增長 1
,生成的二維碼就會添加 4
尺寸,例如 version
是 2
,則生成 25 * 25
的二維碼。svg
參數 error_correction 指定二維碼的容錯係數,分別有如下4個係數:ui
ERROR_CORRECT_L
: 7%的字碼可被容錯spa
ERROR_CORRECT_M
: 15%的字碼可被容錯code
ERROR_CORRECT_Q
: 25%的字碼可被容錯xml
ERROR_CORRECT_H
: 30%的字碼可被容錯圖片
參數 box_size
表示二維碼裏每一個格子的像素大小。
參數 border
表示邊框的格子厚度是多少(默認是4
)。
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
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)