使用zxing生成二维码
1、导入Maven
、、、
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.1.0</version>
</dependency>
、、、
2、工具类主要方法
、、、
/**
* 图形码生成工具
*
* @param contents 内容
* @param barcodeFormat BarcodeFormat对象
* @param format 图片格式,可选[png,jpg,bmp]
* @param width 宽
* @param height 高
* @param margin 边框间距px
* @param saveImgFilePath 存储图片的完整位置,包含文件名
* @return {boolean}
*/
public static boolean encode(String contents, BarcodeFormat barcodeFormat, Integer margin,
ErrorCorrectionLevel errorLevel, String format, int width, int height, String saveImgFilePath) {
boolean bool = false;
BufferedImage bufImg;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(3);
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
hints.put(EncodeHintType.MARGIN, margin);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, barcodeFormat, width, height, hints);
MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
bufImg = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
bool = writeToFile(bufImg, format, saveImgFilePath);
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
/**
* @param outputStream 可以来自response,也可以来自文件
* @param contents 内容
* @param barcodeFormat BarcodeFormat对象
* @param margin 图片格式,可选[png,jpg,bmp]
* @param errorLevel 纠错级别 一般为:ErrorCorrectionLevel.H
* @param format 图片格式,可选[png,jpg,bmp]
* @param width 宽
* @param height 高
*/
public static void encodeOutPutSteam(OutputStream outputStream, String contents, BarcodeFormat barcodeFormat, Integer margin, ErrorCorrectionLevel errorLevel, String format, int width, int height) throws IOException {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(3);
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
hints.put(EncodeHintType.MARGIN, margin);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
BitMatrix bitMatrix = (new MultiFormatWriter()).encode(contents, barcodeFormat, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
outputStream.close();
}
}
}
、、、