1、添加依赖
<!-- 条形码、二维码生成 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
</dependency>
2、工具类 QrCodeUtils
package com.qrcode.demo.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;
public class QrCodeUtils {
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int LOGO_WIDTH = 60;
// LOGO高度
private static final int LOGO_HEIGHT = 60;
/**
* 生成二维码
* @param contents 链接
* @return
*/
public static String createQrCode(String contents)throws Exception{
String binary = null;
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE,QRCODE_SIZE,QRCODE_SIZE,hints);
//1、读取文件转换为字节数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage image = toBufferedImage(bitMatrix);
//转换png格式的IO流
ImageIO.write(image,"png",out);
byte[] bytes = out.toByteArray();
//2、降字节转化为二进制
BASE64Encoder encoder = new BASE64Encoder();
binary = encoder.encodeBuffer(bytes).trim();
}catch (WriterException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return binary;
}
/**
* image流数据处理
* @param matrix
* @return
*/
public static BufferedImage toBufferedImage(BitMatrix matrix)throws Exception{
int width = matrix.getWidth();
int heigth = matrix.getHeight();
BufferedImage image = new BufferedImage(width,heigth,BufferedImage.TYPE_INT_RGB);
for (int x = 0;x < width;x ++){
for (int y = 0;y < width;y ++){
image.setRGB(x,y,matrix.get(x,y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}
}
3、测试
public static void main(String[] args) {
try {
String binary = QrCodeUtils.createQrCode("https://blog.csdn.net/CMEguagua");
System.out.println(binary);
}catch (Exception e){
e.printStackTrace();
}
}
4、前端展示
<div><img src="https://img-blog.csdnimg.cn/2022010623070940619.png"></div>