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?
-
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?Benjamin Gruenbaum– Benjamin Gruenbaum2012-06-07 09:56:20 +00:00Commented Jun 7, 2012 at 9:56
-
+1, nice question :-) made me learn somethingnIcE cOw– nIcE cOw2012-06-09 17:00:12 +00:00Commented Jun 9, 2012 at 17:00
Add a comment
|
1 Answer
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):

8 Comments
Andrew Thompson
See also this example using
GlyphVector for other interesting text/image combinations.whiteberryapps
How do I save the image on my computer?
dacwe
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.stacky
Thanks this worked great, how can we change the text color using hex code and font to arial??
Baruch Atta
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/…
|