且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在java中向图像添加文本?

更新时间:2023-12-05 16:02:52

这很简单,只需从图像中获取 Graphics 对象并将您的字符串绘制到图像上即可.这个例子(和输出图像)就是这样做的:

It's easy, just get the Graphics object from the image and draw your string onto the image. This example (and output image) is doing that:

public static void main(String[] args) throws Exception {
    final BufferedImage image = ImageIO.read(new URL(
        "http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));

    Graphics g = image.getGraphics();
    g.setFont(g.getFont().deriveFont(30f));
    g.drawString("Hello World!", 100, 100);
    g.dispose();

    ImageIO.write(image, "png", new File("test.png"));
}

输出(test.png):