使用python调用zxing库生成二维码图片

(1)     安装Jpype 

用python调用jar包须要安装jpype扩展,在Ubuntu上能够直接使用apt-get安装jpype扩展

$ sudo apt-get install python-jpype
关于使用Jpype调用jar包的方式。请看http://blog.csdn.net/niuyisheng/article/details/9002926 

(2)     得到zxing  jar包 

使用zxing第三方库生成二维码图片,关于zxing的介绍能够看其github地址:https://github.com/zxing/zxing/
我们能够下载源代码编译安装包。也能够直接在网上下载jar包,我的jar包是直接下载的,例如以下:

关于zxing库的使用。能够查看http://mygirl1314520.iteye.com/blog/1912109 

(3)     使用python调用jar 

以下使用zxing库生成QR_CODE的二维码图片:

#!/usr/bin/python
#-*- encoding: utf-8 -*-

from jpype import *

# 启动JVM
startJVM(getDefaultJVMPath(), "-ea", ("-Djava.class.path=%s" % "./javase-2.2.jar:./core-2.2.jar"))

# 载入须要使用到的类型
MultiFormatWriter = JClass("com.google.zxing.MultiFormatWriter")
BarcodeFormat = JClass("com.google.zxing.BarcodeFormat")
BitMatrix = JClass("com.google.zxing.common.BitMatrix")
File = JClass("java.io.File")
BufferedImage = JClass("java.awt.image.BufferedImage")
ImageIO = JClass("javax.imageio.ImageIO")
ByteArrayOutputStream = JClass("java.io.ByteArrayOutputStream")
MatrixToImageWriter = JClass("com.google.zxing.client.j2se.MatrixToImageWriter")
EncodeHintType = JClass("com.google.zxing.EncodeHintType")
Hashtable = JClass("java.util.Hashtable")

StrToEncode = "This is a testing string"
# 设置Margin=0
hints = Hashtable()
hints.put(EncodeHintType.MARGIN, 0)

matrix = MultiFormatWriter().encode(StrToEncode, BarcodeFormat.QR_CODE, 260, 260, hints)
image = MatrixToImageWriter.toBufferedImage(matrix)
ImageIO.write(image, "png", File("test.png"))

# 关闭JVM
shutdownJVM()

(4)     执行 

执行程序得到的图片例如以下。能够使用二维码扫描工具得到二维码里面保存的信息。 

test   


參考文献: 

http://blog.csdn.net/niuyisheng/article/details/9002926:jpype的使用方式 

http://mygirl1314520.iteye.com/blog/1912109:zxing库的使用方式

posted on 2017-04-11 12:24  blfbuaa  阅读(645)  评论(0编辑  收藏  举报