package org.example.cropland.controller;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
public class QRCodeGenerator {
public static void generateQRCodeImage(String text, int width, int height, String filePath, String logoPath)
throws WriterException, IOException {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
// 创建二维码图片
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
// 加载自定义图片
BufferedImage logoImage = ImageIO.read(new File(logoPath));
// 创建一个新的BufferedImage对象,用于合成二维码和自定义图片
BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = combined.createGraphics();
// 将二维码绘制到合成图片中
g.drawImage(MatrixToImageWriter.toBufferedImage(bitMatrix), 0, 0, null);
// 计算自定义图片的位置,使其居中显示在二维码中间
int logoWidth = Math.min(logoImage.getWidth(), width / 6);
int logoHeight = Math.min(logoImage.getHeight(), height / 6);
int x = (width - logoWidth) / 2;
int y = (height - logoHeight) / 2;
// 合成二维码和自定义图片
g.drawImage(logoImage, x, y, logoWidth, logoHeight, null);
g.dispose();
// 将合成的图片保存到文件
ImageIO.write(combined, "PNG", new File(filePath));
}
public static void main(String[] args) {
String websiteURL = "http://39.107.86.110:8080/login/login.html"; // 替换为你的网站链接
int width = 600; // 图像宽度
int height = 600; // 图像高度
String QR_CODE_IMAGE_PATH = "E:\\code.jpg"; // 二维码保存路径
String logoPath = "E:\\demo\\cropland\\src\\main\\resources\\static\\image\\1.jpg"; // 自定义图片路径
try {
generateQRCodeImage(websiteURL, width, height, QR_CODE_IMAGE_PATH, logoPath);
System.out.println("二维码已生成到:" + QR_CODE_IMAGE_PATH);
} catch (WriterException | IOException e) {
System.out.println("创建二维码时出现错误:" + e.getMessage());
}
}
}
二维码生成器
最新推荐文章于 2024-11-13 01:21:01 发布