//生成二维码
private void generatorQrImage(int type, String templateUrl, String merchantName, int merchantId, HttpServletResponse response) throws Exception {
BufferedImage bi = ImageIO.read(new FileInputStream(templateUrl));
int width = bi.getWidth(null);
Graphics2D g = (Graphics2D) bi.getGraphics();
Font font = new Font("微软雅黑", Font.PLAIN, 80);
g.setFont(font);
// 抗锯齿
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 计算文字长度,计算居中的x点坐标
FontMetrics fm = g.getFontMetrics(font);
int textWidth = fm.stringWidth(merchantName);
int widthX = (width - textWidth) / 2;
g.setBackground(Color.WHITE);
g.setColor(Color.BLACK);
g.drawString(merchantName, widthX, 1560);
// 生成二维码
String qrContent = "http://ttgo.net.cn/quickLogin?businessId=" + merchantId + "&type=" + type;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix;
bitMatrix = multiFormatWriter.encode(qrContent, BarcodeFormat.QR_CODE, 300, 300, hints);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", baos);
byte[] data = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(data);
BufferedImage qrCode = ImageIO.read(bais);
// 将生成的二维码渲染到模板中
g.drawImage(qrCode, 910, 1630, 550, 550, null);
g.dispose();
bais.close();
baos.close();
ImageIO.write(bi, "png", response.getOutputStream());
}
生成二维码
最新推荐文章于 2024-05-30 20:21:26 发布