public static void main(String[] args) {
createFontImage("红色", new Font("宋体", Font.BOLD, 50), 400, 400);
}
/**
* 根据str,font的样式将文字变成图片,然后返回一个流
*
* @param str 字符串
* @param font 字体
* @param width 宽度
* @param height 高度
*/
public static ByteArrayOutputStream createFontImage(String str, Font font, Integer width, Integer height) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 创建图片
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.black); //在换成黑色
FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
// 设置画笔字体
g.setFont(font);
int strWidth = metrics.stringWidth(str);
int strHeight = metrics.getHeight();
int top = (height - strHeight) / 2 + metrics.getAscent();//可以上下居中
int left = (width - strWidth) / 2; //左边位置,这样可以左右居中
g.drawString(str, left, top); // 画出字符串,
g.dispose();
//将图片输出到ByteArrayOutputStream中
try {
ImageIO.write(image, "png", os);
} catch (IOException e) {
System.out.printf("IOException:%s", e);
StreamClose.close(os);//出了异常则在内部关闭流,StreamClose是我自己写的关闭流的工具
}
return os;
}
Java通过代码实现将字符文字变成一个图片
最新推荐文章于 2023-09-16 16:08:28 发布