本文是使用 zxing 生成QaCode 生成和解析 二维码的例子
使用maven 测试,需要的 maven 依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
package com.study.zwing;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QaCodeTest {
/**
* 创建Qa_Code 二维码
* @throws Exception
*/
@Test
public void createQacode() throws Exception{
//生成图片的基本参数
int height = 300;
int width = 300;
String format = "png";
String contents = "www.baidu.com"; // 如果在前面加上 http:// 或者 https:// 那么就是打开一个连接,要不然就只是一个普通文本
//定义二维码的参数
Map<EncodeHintType, Object> hits = new HashMap<>();
hits.put(EncodeHintType.CHARACTER_SET, "utf-8"); //字符集
hits.put(EncodeHintType.MARGIN, 2); // 图片空白的大小
hits.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 图片容错等级,一般用M就行了
//创建图片
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hits);
//生成到特定位置
Path path = new File("d:/zxc.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, path);
}
/**
* 解析 Qa_Code 二维码
* @throws Exception
*/
@Test
public void parseQaCode() throws Exception{
File file = new File("d:/zxc.png");
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Map<DecodeHintType, Object> hits = new HashMap<>();
hits.put(DecodeHintType.CHARACTER_SET, "utf-8"); //字符集
Result result = new MultiFormatReader().decode(binaryBitmap, hits);
System.out.println("解析结果为 : " + result.toString());
System.out.println("二维码类型为 : " + result.getBarcodeFormat());
System.out.println("二维码文本为 : " + result.getText());
}
}