Pulpcode

捕获,搅碎,拼接,吞咽

0%

使用python操作二维码

使用python生成二维码需要用到qrcode库,但是此库会依赖到其它库,请按照如下步骤安装:

安装 pil

1
sudo easy_install pil

如果出现如下错误:

1
2
3
4
5
_imagingft.c:73:10: fatal error: 'freetype/fterrors.h' file not found
#include <freetype/fterrors.h>
^
1 error generated.
error: Setup script exited with error: command 'cc' failed with exit status 1

是因为Mac 下所依赖的 FreeType 链接变更问题,解决如下:

1
2
ln -s /usr/local/include/freetype2 /usr/local/include/freetype
sudo easy_install -U pil

安装qrcode

1
sudo easy_install qrcode

打开解释器, import qrcode 无误,则安装成功

可以在shell用如下命令生成一个简单的二维码。

1
2
qr "www.pulpcode.cn" > test.png
qr —help

在python中的类似实现是这样的:

1
2
import qrcode
img = qrcode.make('www.pulpcode.cn')

高级用法

1
2
3
4
5
6
7
8
9
10
11
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data('www.pulpcode.cn')
qr.make(fit=True)

img = qr.make_image()

参数解析:

参数version表示二维码的尺寸大小,范围是1~40,会生成*17+n4**尺寸大小的二维码,比如version是1,尺寸是21,version是,2尺寸是25。
我们一般在手机上生成的二维码,就是version1,也就是 尺寸21。

error_correction是指容错系数,二维码容错率即是指二维码图标被遮挡多少后,仍可以被扫描出来的能力。容错率越高,因为编码过程本身是有沉余的,这也就是为什么有些二维码中间可以有照片,则二维码图片能被遮挡的部分越多。二维码容错率用字母表示,容错能力等级分为:L、M、Q、H四级。

  1. ERROR_CORRECT_L: 7%的字码可被容错
  2. ERROR_CORRECT_M: 15%的字码可被容错
  3. ERROR_CORRECT_Q: 25%的字码可被容错
  4. ERROR_CORRECT_H: 30%的字码可被容错

大多数情况下,建议采用30%的容错率。

box_size 表示二维码里每个格子的像素大小

border参数控制边框的厚度(默认是4,这是最低的规格)

可以带有图片的二维码

之前提到了容错系数,我们需要在二维码的中央方一个图片,就需要将容错系数设置成:ERROR_CORRECT_H

而且二维码的数据主要保存在图片的四个角上,所以一般将图片放在二维码的中央,而且过大的图片是会影响到图片识别的,在程序中我们也进行了缩放。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# -*- coding: utf-8 -*-
import Image
import qrcode

qr = qrcode.QRCode(
version=2,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=1
)
qr.add_data("http://www.pulpcode.cn")
qr.make(fit=True)

qrimg = qr.make_image()
qrimg = qrimg.convert("RGB")

# build in image
bi_img = Image.open("starbucks.png")

# 修正大小
qrimg_w, qrimg_h = qrimg.size
factor = 4
size_w = int(qrimg_w / factor)
size_h = int(qrimg_h / factor)

bi_w, bi_h = bi_img.size
bi_w = bi_w > size_w and size_w or bi_w
bi_h = bi_h > size_h and size_h or bi_h
bi_img = bi_img.resize((bi_w, bi_h), Image.ANTIALIAS)

# 粘贴图片
w = int((qrimg_w - bi_w) / 2)
h = int((qrimg_h - bi_h) / 2)
qrimg.paste(bi_img, (w, h), bi_img)

qrimg.save("qrstarbucks.png")

效果如下:

低俗代码

因为我们的二维码图片是存成png的,所以你的图片也是要png的,而且要注意的是,一定要用正规的png图片(建议用正规的转换软件),否则会报错ValueError: bad transparency mask