61

I need to add some texts to an existing table image (png). Which means that I need to "write" on the image and I need the option to select the text location. How can I do it?

2
  • What are you using to represent the image? Do you already have the image in some format in java or do you want to write a whole java program that gets an image and returns that image with the text written on it from scratch? Commented Jun 7, 2012 at 9:56
  • +1, nice question :-) made me learn something Commented Jun 9, 2012 at 17:00

1 Answer 1

131

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"));
}

Output (test.png):

output

Sign up to request clarification or add additional context in comments.

8 Comments

See also this example using GlyphVector for other interesting text/image combinations.
How do I save the image on my computer?
It's already in the code above. Use ImageIO.write(image, "png", new File("test.png")); It will write the file (test.png) to the current directory.
Thanks this worked great, how can we change the text color using hex code and font to arial??
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.