一、zxing介绍

  zxing是google提供生成、解析一维码、二维码的开源库。

二、使用

2.1 maven pom 配置

    <dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>

2.2 二维码生成

      /**
* 编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode(String contents, int width, int height, String imgPath) {
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height); MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath)); } catch (Exception e) {
e.printStackTrace();
}
}
    /**
* @param args
*/
public static void main(String[] args) {
String imgPath = "/Users/xupengwei/tool/yuanmeng/zxing.png";
String contents = "http://taobao.com";
int width = 300, height = 300;
QrCode.encode(contents, width, height, imgPath);
}

结果

zxing 生成二维码-LMLPHP

2.3 二维码解码

    /**
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); result = new MultiFormatReader().decode(bitmap);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
    public static void main(String[] args) {

        String imgPath = "/Users/xupengwei/tool/yuanmeng/zxing.png";
String decodeContent = QrCode.decode(imgPath);
System.out.println(decodeContent);
}

结果:

http://taobao.com

三、参考文献

1、https://github.com/zxing/zxing

2、API 文档 : https://zxing.github.io/zxing/apidocs/

05-11 18:23