How to add text to an image in Java
In this tutorial, we are going to see how to add text to an image in Java. You just have to get the Graphics object of the image and draw your string on the image. The following example adds the text “Welcome To StackHowTo!” to the image “image.png”.
[st_adsense]
Java Program to add text to an image
import java.awt.*; import java.io.*; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class AddTextToImg { public static void main(String[] args) throws Exception { //read the image BufferedImage image = ImageIO.read(new File("image.png")); //get the Graphics object Graphics g = image.getGraphics(); //set font g.setFont(g.getFont().deriveFont(25f)); //display the text at the coordinates(x=50, y=150) g.drawString("Welcome To WayToLearnX!", 50, 150); g.dispose(); //write the image ImageIO.write(image, "png", new File("image1.png")); } }
Input:
Output:
[st_adsense]