1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.2</version>
<scope>compile</scope>
</dependency>
2.代码
package org.example.qrcode;
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.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MyQrcode {
public static MultipartFile generateQrCode(String content, int width, int height) {
MultipartFile multipartFile = null;
try {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
BitMatrix bitMatrix = null;
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,"png",new File("./ad.png"));
ImageIO.write(bufferedImage, "png", baos);
byte[] imageBytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
String fileName = "qrcode.png";
multipartFile = new MockMultipartFile("file", fileName, "image/png", bais);
} catch (Exception e) {
e.printStackTrace();
}
return multipartFile;
}
public static void main(String[] args) throws IOException {
generateQrCode("中国", 300, 300);
}
}
3.说明
代码中有两次ImageIO.write的方法,第一个是把二维码图片存储到了指定的路径,适合本地测试;第二个是把文件流通过multipartFile返回了,适合生成二维码文件流后上传到服务器的操作。两个方法留一个即可。