PIL:Python Imaging Library(图像处理标准库)和Qrcode:二维码生成

安装PIL

Mac或Linux安装命令:sudo easy_install PIL

如果报错:fatal error: 'freetype/fterrors.h' file not found

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

ln -s /usr/local/include/freetype2 /usr/local/include/freetype

sudo easy_install -U pil

如果出现问题:decoder jpeg not available

卸载你的PIL

下载libjpeg:http://www.ijg.org/files/jpegsrc.v7.tar.gz

安装libjpeg:

$ tar zxvf jpegsrc.v7.tar.gz 
$ cd jpeg-7 
$ ./configure --enable-shared --enable-static 
$ make 
$ sudo make install

下载PIL: http://effbot.org/downloads/Imaging-1.1.7.tar.gz

编辑setup.py,设置:

JPEG_ROOT = libinclude("/usr/local")

ZLIB_ROOT = libinclude("/usr/local")

安装PIL

$ python setup.py build 
$ sudo python setup.py install --optimize=1 
$ python selftest.py - Run the selftest to confirm PIL is installed ok 
$ sudo python setup.py install 

重启IDLE

使用例可参考:

实例

详细了解PIL,请参考PIL官方文档:

http://effbot.org/imagingbook/

Qrcode:生成二维码

安装 qrcode:sudo easy_install qrcode

测试代码(在命令行输入):qr "test" > test.png

python代码:

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://wx341.vshangtong.com/wxapi.php?ac=photo&tid=341&from=timeline&isappinstalled=0")
qr.make(fit=True)
 
img = qr.make_image()
img = img.convert("RGBA")
 
icon = Image.open("pvg.png")
 
img_w, img_h = img.size
factor = 4
size_w = int(img_w / factor)
size_h = int(img_h / factor)
 
icon_w, icon_h = icon.size
if icon_w > size_w:
    icon_w = size_w
if icon_h > size_h:
    icon_h = size_h
icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
 
w = int((img_w - icon_w) / 2)
h = int((img_h - icon_h) / 2)
img.paste(icon, (w, h), icon)
 
img.save("dhqme_qrcode.png")

结果:

posted @ 2015-04-25 15:03  dayday+up  阅读(1544)  评论(0编辑  收藏  举报