二维码和条形码生成
前言
之前说了微信小程序生成微信小程序码,现在说一下普通的二维码的生成。
(这些都是亲测,都可以使用)
导入依赖(maven)
<!--Zxing 条形码二维码生成和解析工具-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
自定义一个工具类
package com.miniapp.common.utils;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
/**
* @author zwh
* @date 2022/4/10 17:04
*/
@Slf4j
public class QrCodeUtil {
/**
* 默认宽度
*/
private static final int WIDTH = 300;
/**
* 默认高度
*/
private static final int HEIGHT = 300;
/**
* 默认文件格式
*/
private static final String FORMAT = "png";
/**
* 一些默认参数
*/
private static final Map<EncodeHintType, Object> HINTS = new HashMap();
static {
// 字符编码
HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 二维码与图片边距
HINTS.put(EncodeHintType.MARGIN, 2);
}
/**
* 生成图片的条形码
*
* @param content 内容
* @param paths 路径
*/
public static void generateBarCodeFile(String content, String paths) {
Code128Writer writer = new Code128Writer();
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, HEIGHT, HINTS);
Path path = Paths.get(paths);
if (!StrUtil.isEmpty(content)) {
try {
MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
} catch (IOException e) {
log.error("生成条形码失败:{}", e.getMessage());
}
}
}
/**
* 生成文件流的条形码
*
* @param content 内容
* @param response 响应体
* @return 流
*/
public static OutputStream generateBarCodeStream(String content, HttpServletResponse response) {
Code128Writer writer = new Code128Writer();
OutputStream outputStream = null;
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, HEIGHT, HINTS);
if (!StrUtil.isEmpty(content)) {
try {
// 字节输出流
outputStream = response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, outputStream);
return outputStream;
} catch (IOException e) {
log.error("生成条形码失败:{}", e.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error("流关闭失败:{}", e.getMessage());
}
}
}
}
return null;
}
/**
* 生成base64的二维码
*
* @param content 内容
* @return base64二维码
*/
public static String generateBarCodeBase64(String content) {
String base64;
ByteArrayOutputStream os = new ByteArrayOutputStream();
Code128Writer writer = new Code128Writer();
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, HEIGHT, HINTS);
if (!StrUtil.isEmpty(content)) {
try {
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(bufferedImage, FORMAT, os);
base64 = Base64.encode(os.toByteArray());
return base64;
} catch (Exception e) {
log.error("生成二维码失败:{}", e.getMessage());
} finally {
try {
os.flush();
os.close();
} catch (IOException e) {
log.error("流关闭失败:{}", e.getMessage());
}
}
}
return null;
}
/**
* 生成图片的二维码
*
* @param content 内容
* @param paths 路径
*/
public static void generateQrCodeFile(String content, String paths) {
MultiFormatWriter writer = new MultiFormatWriter();
if (!StrUtil.isEmpty(content)) {
try {
// 字节输出流
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
Path path = Paths.get(paths);
MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
} catch (Exception e) {
log.error("生成二维码失败:{}", e.getMessage());
}
}
}
/**
* 生成文件流的二维码
*
* @param content 内容
* @param response 响应体
* @return 流
*/
public static OutputStream generateQrCodeStream(String content, HttpServletResponse response) {
MultiFormatWriter writer = new MultiFormatWriter();
OutputStream outputStream = null;
if (!StrUtil.isEmpty(content)) {
try {
// 字节输出流
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
outputStream = response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, outputStream);
return outputStream;
} catch (Exception e) {
log.error("生成二维码失败:{}", e.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error("流关闭失败:{}", e.getMessage());
}
}
}
}
return null;
}
/**
* 生成base64的二维码
*
* @param content 内容
* @return base64二维码
*/
public static String generateQrCodeBase64(String content) {
String base64;
ByteArrayOutputStream os = new ByteArrayOutputStream();
if (!StrUtil.isEmpty(content)) {
try {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(bufferedImage, FORMAT, os);
base64 = Base64.encode(os.toByteArray());
return base64;
} catch (Exception e) {
log.error("生成二维码失败:{}", e.getMessage());
} finally {
try {
os.flush();
os.close();
} catch (IOException e) {
log.error("流关闭失败:{}", e.getMessage());
}
}
}
return null;
}
}
这些分别生成条形码和二维码,包括生成本地的,base64的,和文件流的,按需求进行调用方法即可。
注意:生成文件流的需要传参HttpServletResponse 这一点需要注意
类似
@GetMapping("getQrcode")
public OutputStream getQrcode (HttpServletResponse response) throws IOException {
OutputStream s = CodeUtil.generateQrCodeStream("测试文件流", response);
return s;
}
扩展
如果你想让你的二维码内容进行加密,你完全可以使用hutool包的加密工具类进行加密解密。
也可以选择对称加密和非对称加密,这是你自己进行取舍的。
package com.study.mybatisplus.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
/**
* @author : zwh
* @date : 2022/4/11 10:54
* 对称加密
*/
public class SecurityUtil {
/**
* 密钥
*/
private static final String STR_KEY = "mybatis_plus_security_key";
/**
* 生成密钥
*
* @return 密钥
*/
private static byte[] getKey() {
byte[] byteKey = StrUtil.bytes(STR_KEY);
return SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), byteKey).getEncoded();
}
/**
* 获得加密后的字符串
*
* @param content 需要加密的内容
* @return 加密后的字符串
*/
public static String getEncryptStr(String content) {
DES des = SecureUtil.des(SecurityUtil.getKey());
return des.encryptHex(content);
}
/**
* 获得解密后的内容
*
* @param encryptStr 密文
* @return 解密后的内容
*/
public static String getDecryptStr(String encryptStr) {
DES des = SecureUtil.des(SecurityUtil.getKey());
return des.decryptStr(encryptStr);
}
}
具体的细节就需要你自己慢慢进行取舍了。
其实二维码可以使用hutool的QrCodeUtil;其中本质也是引用的是ZXing的jar包;但是可以省事,省了好多事情,直接哪来就可以用了。