/**
* 把文字转为图片
*
* @param text
* 要写的内容
* @throws IOException
*/
public static void textToImg(String text) throws IOException {
int len = text.length();
int fontSize = 1000;
int width = len * fontSize;
Font font = new Font("楷体", Font2D.NATIVE_RANK, fontSize);
FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
int height = fm.getHeight();// 获得字的高度
System.out.println(height);
BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffer.createGraphics();
g.setBackground(Color.red);
g.clearRect(0, 0, width, height);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形。此操作不使用当前绘图模式。 如果不加这一段,背景会一直是黑色(默认色)
g.setFont(font);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));//设置文字透明度
g.setColor(new Color(Integer.parseInt("000000", 16)));
g.drawString(text, 0, height - fontSize / 5);//把字的高度减去字体的五分之一,基本可以保持居中
g.dispose();
File file = new File("C://2.jpg");
ImageIO.write(buffer, "jpg", file);//保存
}