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?– Benjamin GruenbaumJun 7, 2012 at 9:56
-
+1, nice question :-) made me learn something– nIcE cOwJun 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
):
-
2See also this example using
GlyphVector
for other interesting text/image combinations. Jun 7, 2012 at 10:51 -
-
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.– dacweJun 7, 2012 at 11:23 -
@user1441845 Post another question about that, but just a hint, use
JFileChooser
:-)– dacweJun 8, 2012 at 21:54 -
1Thanks this worked great, how can we change the text color using hex code and font to arial??– stackyMar 26, 2017 at 8:27