场景:前端库冲突,不能生成二维码,让后端生成二维码
这个方法能够直接用,我是以base64的格式返回给前端
依赖:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version> <!-- 或者使用最新的版本 -->
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version> <!-- 或者使用最新的版本 -->
</dependency>
代码:
/**
* @author qiu
* @date 2023/11/26--17:07
* 二维码生成
**/
public class QRTest {
public static void main(String[] args) {
String s = generateBase64QRCodeWithLogo("来了,小老弟", "C:\Users\Administrator\Downloads\下载.jpg");
System.out.println(s);
}
public static String generateBase64QRCodeWithLogo(String qrCodeText, String logoUrl) {
try {
int size = 300;
// 生成二维码
Map<EncodeHintType, Object> hintMap = new HashMap<>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hintMap.put(EncodeHintType.MARGIN, 2);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, size, size, hintMap);
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
// 设置二维码颜色
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
image.setRGB(i, j, byteMatrix.get(i, j) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
}
}
// 从URL添加logo
//URL url = new URL(logoUrl);
//BufferedImage logo = ImageIO.read(url);
//本地路径添加logo
BufferedImage logo = ImageIO.read(new File(logoUrl));
//并根据需要调整大小
int logoSize = Math.min(matrixWidth / 5, matrixWidth / 5);
int x = (matrixWidth - logoSize) / 2;
int y = (matrixWidth - logoSize) / 2;
// 如果logo大于二维码,则调整其大小
if (logo.getWidth() > logoSize || logo.getHeight() > logoSize) {
logo = resizeImage(logo, logoSize, logoSize);
}
graphics.drawImage(logo, x, y, logoSize, logoSize, null);
// 将带有徽标的二维码保存到ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
baos.flush();
baos.close();
graphics.dispose();
// 转换为Base64
byte[] imageBytes = baos.toByteArray();
return Base64.getEncoder().encodeToString(imageBytes);
} catch (IOException | WriterException e) {
e.printStackTrace();
return null;
}
}
private static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = outputImage.createGraphics();
graphics2D.drawImage(resultingImage, 0, 0, null);
graphics2D.dispose();
return outputImage;
}
}
使用以上代码即可。