Python二维码生成库qrcode示例

原创
2016/03/30 14:21
阅读数 798

二维码简称 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

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部