//文字转图片 public static void createImage(String str, Font font, File outFile, Integer width, Integer height) throws Exception { // 创建图片 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); g.setClip(0, 0, width, height); //白色背景 g.setColor(Color.white); g.fillRect(0, 0, width, height); //文字蓝色 g.setColor(Color.BLUE); // 设置画笔字体 g.setFont(font); /** 用于获得垂直居中y */ Rectangle clip = g.getClipBounds(); FontMetrics fm = g.getFontMetrics(font); int ascent = fm.getAscent(); int descent = fm.getDescent(); int x = clip.x + (clip.width - fm.stringWidth(str)) / 2; int y = (clip.height - (ascent + descent)) / 2 + ascent; g.drawString(str, x, y); g.dispose(); // 输出png图片 ImageIO.write(image, "png", outFile); }
//调用方式
createImage("A02", new Font("宋体", Font.BOLD, 95), new File("D://TEST.png"), 200, 200);
结果如下