(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
$ 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
(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) 运行
运行程序得到的图片如下,可以使用二维码扫描工具得到二维码里面保存的信息。参考文献:
jpype的使用方式:http://blog.csdn.net/niuyisheng/article/details/9002926
zxing库的使用方式:http://mygirl1314520.iteye.com/blog/1912109