本文共 2900 字,大约阅读时间需要 9 分钟。
private static final String URL = "D:/test/template.png";public static String certificateBuilder(String nickname, BigDecimal totalAmount) { //得到图片缓冲区 FileInputStream fileInputStream = null; String savePath = ""; try { File file = new File(URL); if (!file.exists()) { log.info("模板不存在"); } else { fileInputStream = new FileInputStream(file); BufferedImage image = ImageIO.read(fileInputStream); BufferedImage image2 = ImageIO.read(new File("D:/test/stamp.png")); //获取图片的宽 int width = image.getWidth(null); //获取图片的高 int height = image.getHeight(null); log.info("模板位置:{}.宽:{}.高:{}.", URL, width, height); //初始化画板 BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //得到它的绘制环境 Graphics2D g2 = (Graphics2D) bi.getGraphics(); g2.fillRect(0, 0, width, height); //设置颜色 g2.setColor(Color.WHITE); // 将图片大小设置为大约4cm*4cm 具体根据纸张大小设定 g2.drawImage(image, 0, 0, width, height, null); g2.drawRect(0, 0, width, height); g2.setFont(new Font("微软雅黑", Font.PLAIN, 30)); g2.setColor(Color.gray); g2.drawString("证书编号:H11111122222233333", 315, 410); //设置背景颜色 g2.setColor(Color.BLACK); //向图片上写字符串 g2.setFont(new Font("微软雅黑", Font.PLAIN, 42)); g2.drawString("大慈善家", 320, 570); g2.setFont(new Font("微软雅黑", Font.PLAIN, 42)); g2.drawString("2020年9月20日", 720, 1330); g2.setFont(new Font("微软雅黑", Font.PLAIN, 42)); g2.setColor(Color.RED); g2.drawString("5.12元", 450, 1030); //盖章 g2.drawImage(image2, 810, 1174, image2.getWidth(null), image2.getHeight(null), null); // 合成图片 StringBuffer path = new StringBuffer(); path.append("D:/test/"); path.append(UUIDUtils.gen()); path.append("-"); path.append(nickname); path.append(".png"); boolean bool = ImageIO.write(bi, "PNG", new FileOutputStream(path.toString())); log.info("结果:{}.", bool); if (bool) { savePath = path.toString(); } } } catch (Exception e) { log.error("生成图片错误", e); } finally { //关流 if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return savePath; } }
转载地址:http://bicgn.baihongyu.com/