Python二维码生成库qrcode示例
二維碼簡稱 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.pngExample:
import qrcodeqr = 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 的二維碼。
參數 error_correction 指定二維碼的容錯系數,分別有以下4個系數:
ERROR_CORRECT_L: 7%的字碼可被容錯
ERROR_CORRECT_M: 15%的字碼可被容錯
ERROR_CORRECT_Q: 25%的字碼可被容錯
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.svgOr in Python:
import qrcode import qrcode.image.svgif 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 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 the background of the SVG with white:
qrcode.image.svg.SvgFillImage qrcode.image.svg.SvgPathFillImagePure 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-pngFrom your command line:
qr --factory=pymaging "Some text" > test.pngOr 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
總結
以上是生活随笔為你收集整理的Python二维码生成库qrcode示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在word文档中如何修改字体
- 下一篇: thunder.exe是什么