[TOC]
说明
本文介绍使用zxing
来生成和解析二维码。
maven坐标如下:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
1 zxing生成二维码示例
/**
* 生成二维码并写到指定的输出流
*
* @param width
* 二维码宽度
* @param height
* 二维码高度
* @param content
* 二维码内容
* @param dest
* 输出目标,可以是
* {@link FileOutputStream}、{@link ServletOutputStream}等任何输出流
* @throws IOException
* @throws WriterException
*/
public void generateQRCode(int width, int height, String content, OutputStream dest)
throws IOException, WriterException {
Map<EncodeHintType, Object> map = new HashMap<>();
// 编码方式
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 纠错级别--中级
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 内边距
map.put(EncodeHintType.MARGIN, 2);
// 生成二维码
BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, map);
// 写入到任何输出流皆可
MatrixToImageWriter.writeToStream(matrix, "png", dest);
}
2 zxing解析二维码示例
/**
* 从输入流解析二维码
*
* @param inputStream
* @return
* @throws IOException
* @throws NotFoundException
*/
@SuppressWarnings("unchecked")
public Result parseQRCode(InputStream inputStream) throws IOException, NotFoundException {
@SuppressWarnings("rawtypes")
Map map = new HashMap();
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
BinaryBitmap binaryBitmap = null;
BufferedImage bufferedImage = ImageIO.read(inputStream);
binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
Result result = new MultiFormatReader().decode(binaryBitmap, map);
return result;
}
3 一个基于zxing第三方开源项目
地址:https://github.com/kenglxn/QRGen
使用示例:
QRCode.from("https://github.com/kenglxn/QRGen")//
.withSize(400, 400)//
.withHint(EncodeHintType.CHARACTER_SET, "UTF-8")//
.withErrorCorrection(ErrorCorrectionLevel.M)//
.withHint(EncodeHintType.MARGIN, 2)//
.writeTo(new FileOutputStream(new File("/Users/hylexus/tmp/t.png")));