首页 > Script > 用 python 生成和解码二维码图片

用 python 生成和解码二维码图片

[总点击:488次]
2010年1月4日

了解了一下二维码的一些知识,感到很神奇哈,指甲盖那么大一块的二维码居然可以存放 500 多个汉字,呵呵如果书籍这样印刷的话是不是要少用些纸张呢? 这个东西据说在现实中用处还挺大的,很多手机都支持拍摄和解读二维码,并且很多人把自己的个人信息也放在里面,印一张包含自己各种信息的二维码图片的名片是不是很酷呢?呵呵,鉴于可能有此需要,我就试着找了一下看看有没有什么 python 的二维码 lib,嘿嘿,还真有,pyqrcodec 就是这样一个 python lib,archlinux 下用 yaourt -S pyqrcodec 就可以安装,其他发行版的可能类似,就不详述了。

看了一下 pyqrcodec 的文档,用法其实很简单,xiooli 顺手写了一个小脚本,实现了 QR 二维码图片的生成和解码,下面是一张例图:
a
生成这张例图的命令和解码的命令如下:

xiooli@XIOOLI> python qrcode.py -e "hello,大家好,我是 xiooli!" ./a.png 
generated file: ./a.png
xiooli@XIOOLI> python qrcode.py -d ./a.png
QR_IMAGEREADER_DECODED, QR_FORMATINFO_UNRECOVERABLE,
get text: hello,大家好,我是 xiooli!

qrcode.py 的源码:

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
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name:     qrcode.py
# Author:   xiooli <xioooli[at]yahoo.com.cn>
# Site:     http://joolix.com
# Licence:  GPLv3
# Version:  100104
 
'''generate and decode qrcode pictures'''
 
import PyQrcodec as pqr
import sys
 
def gen_qrpic(text, file):
    '''generate a qrcode file contains the given text'''
    stat, img = pqr.encode(text)
    if stat:
        img.save(file)
        return file
    else:
        print "failed to generate qrcode picture."
def qrdecode(file):
    '''decode the qrcode picture'''
    stat, text = pqr.decode(file)
    if stat:
        return text
    else:
        print "failed to decode the qrcode picture."
 
if __name__ == "__main__":
    args = sys.argv
    if len(args) == 1 or args[1] == '-h' or args[1] == '--help':
        print "encode: " + args[0] + " -e [text] [image file]"
        print "decode: " + args[0] + " -d [imgae file]"
    elif args[1] == '-e':
        try:
            print "generated file: " + gen_qrpic(args[2],args[3])
        except:
            pass
    elif args[1] == '-d':
        try:
            print "get text: " + qrdecode(args[2])
        except:
            pass
    else:
        print 'unrecoded arguments'

想为自己名片加上二维码信息的童鞋们不用愁咯,^^

Script , ,

  1. ooo
    2010年1月5日13:32 | #1

    我也要试试

  2. 2010年1月10日15:36 | #2

    这个JS挺好玩的~

  3. xiooli
    2010年1月12日21:52 | #3

    这个不是js阿,是python

  4. 2010年1月13日15:26 | #4

    垃圾八五互联,骗子IDC公司,套人购买空间,不让人绑定域名,请大家注意了,现在给大家通报一下.

  5. 2010年1月13日16:55 | #5

    博主的才华相当的GOOD

  6. 2010年1月16日16:07 | #6

    写得不错

本文的评论功能被关闭了.