代码实现#
public static String generateQRCodeFile(String url, int height, int width, String imageType, int hint){
try {
BitMatrix matrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, width, height, getHints(hint));
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
BufferedImage distinctImage = removeWhiteBorder(image);
int disHeight = distinctImage.getHeight();
int disWidth = distinctImage.getWidth();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if(disHeight < height || disWidth < width){
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = newImage.createGraphics();
AffineTransform af = new AffineTransform();
af.scale(width * 1.0 / disWidth, height * 1.0 / disHeight);
graphics.drawImage(distinctImage, af, null);
graphics.dispose();
ImageIO.write(newImage, imageType, outputStream);
}else{
ImageIO.write(distinctImage, imageType, outputStream);
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
FileItem fileItem = MtgiCommUtil.createFileItem(inputStream, "file." + imageType);
FileUtil fileUtil = SpringUtil.getBean(FileUtil.class);
return fileUtil.getFileId(fileItem);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static java.util.Map<EncodeHintType, Object> getHints(int hint) {
java.util.Map<EncodeHintType, Object> hints = new java.util.HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, hint);
return hints;
}
private static BufferedImage removeWhiteBorder(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int leftMost = width;
int rightMost = 0;
int topMost = height;
int bottomMost = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (image.getRGB(x, y) != -1) {
leftMost = Math.min(leftMost, x);
rightMost = Math.max(rightMost, x);
topMost = Math.min(topMost, y);
bottomMost = Math.max(bottomMost, y);
}
}
}
int newWidth = rightMost - leftMost + 1;
int newHeight = bottomMost - topMost + 1;
BufferedImage newImage = new BufferedImage(newWidth, newHeight, image.getType());
for (int y = topMost; y <= bottomMost; y++) {
for (int x = leftMost; x <= rightMost; x++) {
newImage.setRGB(x - leftMost, y - topMost, image.getRGB(x, y));
}
}
return newImage;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了