How to add text to an image in java?
Asked Answered
S

1

60

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?

Silhouette answered 7/6, 2012 at 9:54 Comment(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?Urbain
+1, nice question :-) made me learn somethingKidskin
P
129

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

Phillips answered 7/6, 2012 at 9:57 Comment(8)
See also this example using GlyphVector for other interesting text/image combinations.Hyperopia
How do I save the image on my computer?Silhouette
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.Phillips
@user1441845 Post another question about that, but just a hint, use JFileChooser :-)Phillips
Works like a charm :) But this doesn't wrap the text to the size of the image. If the text width is larger than the width of the image, text gets cropped. Is there any way we can fit the text into the image?Depolarize
@Depolarize Good question but as always post another question to help the community! :) (..or look at this PO post!)Phillips
Thanks this worked great, how can we change the text color using hex code and font to arial??Heft
Stacky: to change text attributes, see docs.oracle.com/javase/8/docs/api/java/awt/Graphics.html and also this: docs.oracle.com/javase/8/docs/api/java/awt/font/…Beni

© 2022 - 2024 — McMap. All rights reserved.