I'm trying to add text to an image using an example I found on this question: How to add text to an image in java?
This is the code I'm trying. I modified it from the example to fit my own test case (changed the file names and made ImageIO
read from a File
instead of a URL
. I also changed the coordinates to (0,0)
so the text would appear at the top-left of the image).
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class AddText {
public static void main(String[] args) throws IOException {
String text = "CUSTOM TEXT HERE";
BufferedImage image = ImageIO.read(new File("screenshot.png"));
Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(30f));
g.setColor(Color.BLUE);
g.drawString(text, 0, 0);
g.dispose();
ImageIO.write(image, "png", new File("out.png"));
}
}
But when I run the program, all I get in the output file is the same image that was in the input file.
If I use the exact cut-and-paste code from the example at the question linked above, it works. I only changed a few things to fit my situation, but the fundamental calls to the methods are the same, and this doesn't work for me.
Any ideas on why this doesn't work?