本文是基于google的zxing简单的生成和解析二维码的demo,直接上代码了
package com.summer.test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
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;
/**
* @author summer
* @version 创建时间:2018年10月17日 下午12:14:43 类说明
*/
public class QRUtils {
/**
* @Title: getQRCode
* @Description: TODO(根据指定内容生成二维码)
* @param content(二维码中的内容)
* @param dir(二维码生成的路径)
* @return void 返回类型
* @throws
*/
public static void getQRCode(String content, String dir) {
int width = 300;
int height = 300;
String format = "png";
// content = new String(content.getBytes("UTF-8"), "ISO-8859-1");
// 定义二维码的参数
HashMap<EncodeHintType, Comparable> map = new HashMap<EncodeHintType, Comparable>();
// 设置编码
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 设置纠错等级
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
map.put(EncodeHintType.MARGIN, 2);
try {
// 生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, map);
Path file = new File(dir+"qrcode.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
System.out.println("二维码生成完毕path:" + file.toFile().getPath());
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @Title: parseQRCode
* @Description: TODO(解析二维码)
* @param filePath
* @return void 返回类型
* @throws
*/
public static void parseQRCode(String filePath) {
try {
MultiFormatReader multiFormatReader = new MultiFormatReader();
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);
//定义二维码参数
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
//获取读取二维码结果
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Result result = multiFormatReader.decode(binaryBitmap, hints);
System.out.println("读取二维码: " + result.toString());
System.out.println("二维码格式: " + result.getBarcodeFormat());
System.out.println("二维码内容: " + result.getText());
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String content="hello world 测试二维码";
String path = "D:\\";
getQRCode(content, path);
parseQRCode(path+"qrcode.png");
}
}
下图二维码是上面代码生成的,有兴趣可以拿起你的手机相机扫描就能得到里面的信息是“hello world 测试二维码”这段文字
附件是需要的工程和jar