//生成QR二维码
import com.google.zxing.EncodeHintType;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.*;
import java.util.Base64;
@Test void test() throws IOException { //二维码信息 String url = "path"; //设置宽度和高度 int width = 240, height = 240; //设置边框值 int margin = 1; //根据设置的参数生成字节输出流 ByteArrayOutputStream out = QRCode.from(url).withHint(EncodeHintType.MARGIN, margin).to(ImageType.JPG).withSize(width, height).stream(); //可以简单生成 //ByteArrayOutputStream out = QRCode.from(url).to(ImageType.PNG).stream(); //获取字节数组 byte[] data = out.toByteArray(); //指定存储位置 String imagePath = "C:\\Users\\LZW\\Desktop\\new.jpg"; //判断文件是否存在,如果存在删除 File file = new File(imagePath); if (file.exists()) { file.delete(); } //写入文件 OutputStream oute = new FileOutputStream(new File(imagePath)); oute.write(data); oute.flush(); oute.close(); //转base64 注意前缀data:image/jpg;base64, String imageBase64 = Base64.getEncoder().encodeToString(data); System.out.println(imageBase64); }
QRcode二维码依赖
<dependency> <groupId>net.glxn.qrgen</groupId> <artifactId>javase</artifactId> <version>2.0</version> </dependency>