我想用 Java 创建一个 PNG 图像。在这张图片中,我想显示一些随机文本。Normaly 我会创建这样的图片:
BufferedImage bi = new BufferedImage(300,300,BufferedImage.TYPE_INT_ARGB);
bi.getGraphics().drawString("Hello world", 0, 0);
ImageIO.write(bi, "png", File.createTempFile("out", ".png"));
我知道我可以使用以下代码计算字符串长度:
bi.getGraphics().getFontMetrics().stringWidth("Hello world");
但要执行此操作,我需要一个图形对象(我从 BufferedImage 中获取)。所以我必须先声明 BufferedImage,然后才能使用 stringWidth。
结果是,图像比需要的大得多。
我看到的唯一方法是创建一个“虚拟 BufferedImage”。所以我可以计算所需的宽度和高度,然后我可以创建一个适合的 BufferedImage。
我找不到更好的解决方案,但也许有人可以帮助我。
非常感谢。