一. springboot引入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.1</version>
</dependency>
二. 代码参考
注:可直接复制使用(SimpleUpload.upload为七牛云上传接口)
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.CharacterSetECI;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.mfds.utils.AccountMgr;
import com.mfds.utils.SimpleUpload;
import org.springframework.util.ClassUtils;
/**
- @Description: 二维码生成工具类
- @Author: Administrator
- @CreateDate: 2018/9/12 11:53
- @Version: 1.0
/
public class QrCodeCreateUtil {
/*-
生成包含字符串信息的二维码图片
-
@param laborId 劳工id
-
@throws WriterException
-
@throws IOException
*/
public static String createQrCode(String laborId) throws WriterException, IOException{
String content = “https://zhuchuan.net/ScanQRCodeShow/index.html?laborId=”+laborId;//二维码包含的内容
int qrCodeSize = 90;//二维码大小
String imageFormat = “png”;//需要生成的二维码类型(目前固定png)
//二维码参数基本设置
Map<EncodeHintType, Object> hints = new HashMap<>();
//设置编码为UTF-8
hints.put(EncodeHintType.CHARACTER_SET, CharacterSetECI.UTF8);
//设置二维码纠错等级
// L:7%纠错率 M:15%纠错率 Q:25%纠错率 H:30纠错率 纠错率越高越容易识别出来,但是纠错率越高识别速度越慢
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置二维码白边的范围(此值可能不生效)
hints.put(EncodeHintType.MARGIN, 1);
//设置生成的图片类型为QRCode
BarcodeFormat format = BarcodeFormat.QR_CODE;
//生成二维码对应的位矩阵对象
BitMatrix matrix = new MultiFormatWriter().encode(content, format, qrCodeSize, qrCodeSize);
//设置位矩阵对象转图片的参数(前景色,背景色)
MatrixToImageConfig config = new MatrixToImageConfig(Color.black.getRGB(), Color.white.getRGB());
//位矩阵对象转BufferedImage对象
BufferedImage qrcode = MatrixToImageWriter.toBufferedImage(matrix, config);//临时生成个文件夹存放二维码
String parentFile = ClassUtils.getDefaultClassLoader().getResource("").getPath().split(“target”)[0] + “/temp”;
File file = new File(parentFile);
if (!file.exists()) {
file.mkdirs();
}
//该路径下存放的临时二维码图片名称
parentFile += “/” + System.currentTimeMillis() +".png";
File file1 = new File(parentFile);
ImageIO.write(qrcode, imageFormat, file1);
SimpleUpload.upload(file1, laborId + “qrCode” + file1.getName(), AccountMgr.BUCKET_NAME);//2019-08-01修改,调整了生成路径
file1.delete();
//最终路径为:7牛云正式库域名/劳工id + 固定类型名(如二维码标识) + 临时存放的图片名称如:时间戳.png
return AccountMgr.NINIUYUN_URL + laborId+ “qrCode” + file1.getName();//2019-08-01修改,调整了生成路径
}
-
}