(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包
$ wget http://repo1.maven.org/maven2/com/google/zxing/javase/2.2/javase-2.2.jar $ wget http://repo1.maven.org/maven2/com/google/zxing/core/2.2/core-2.2.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) 運行
運行程序得到的圖片如下,可以使用二維碼掃描工具得到二維碼裏面保存的信息。
參考文獻:
http://blog.csdn.net/niuyisheng/article/details/9002926:jpype的使用方式