需求:根据设备信息生成二维码,放在模板图片上,返回到前端
一 生成二维码工具类
package com.example.gatewayacquisitionsystem.util;
import cn.hutool.core.lang.Assert;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Component;
import sun.font.FontDesignMetrics;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
/**
* FileName: QRCodeUtil
* Author: xuan zongjun
* Date: 2022/6/15 11:00
* Description: 二维码生成工具类
*/
@Component
public class QRCodeUtil {
/**
* 创建二维码
* @param charSet 编码方式
* @param content 二维码内容
* @param qrWidth 二维码长度
* @param qrHeight 二维码高度
* @return
*/
public static BufferedImage createImage(String charSet, String content, int qrWidth, int qrHeight){
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, charSet);
hints.put( EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,qrWidth , qrHeight, // 修改二维码底部高度
hints);
} catch (WriterException e) {
e.printStackTrace();
}
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}
/**
* 对已经生成好的二维码设置logo
* @param source 二维码
* @param logo logo图片
* @param logoWidth logo宽度
* @param logoHeight logo高度
*/
public static void insertLogoImage(BufferedImage source,Image logo,int logoWidth,int logoHeight){
Graphics2D graph = source.createGraphics();
int qrWidth = source.getWidth();
int qrHeight = source.getHeight();
int x = (qrWidth - logoWidth) / 2;
int y = (qrHeight - logoHeight) / 2;
graph.drawImage(logo, x, y, logoWidth, logoHeight, null);
Shape shape = new RoundRectangle2D.Float(x, y, logoWidth, logoHeight, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 缩小logo图片
* @param logoPath
* @param logoWidth
* @param logoHeight
* @return
*/
public static Image compressLogo(String logoPath, int logoWidth, int logoHeight){
File file = new File(logoPath);
if (!file.exists()) {
System.err.println("" + logoPath + " 该文件不存在!");
return null;
}
Image original = null;
try {
original = ImageIO.read(new File(logoPath));
} catch (IOException e) {
e.printStackTrace()