1

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?

Community
  • 1
  • 1
David Mordigal
  • 399
  • 3
  • 19

2 Answers2

0

You have specified your x and y coordinate as 0 and 0 in the drawString() function. According to the function the base line of the left most character is at position (x, y) in this graphics contexts's coordinate system. So your text gets drawn where it is not visible, somewhere above the image. Use g.drawString(text, 0,40) to get in the top left corner.

Kuldeep Dubey
  • 1,097
  • 2
  • 11
  • 33
0

You need to set the color to something besides BG for the String to show. private static void end(Graphics g)

{ g.setColor(BG);

g.fillRect(0, 0, 900, 900); g.setFont(new Font("TimesRoman", Font.PLAIN, 40)); g.setColor(FG) // Here g.drawString("GAME OVER!!", 10, 30);

}

Ashwin Golani
  • 498
  • 3
  • 10