Reputation: 311
I am running into some issues while wanting to write some text on an image. As I looked, it could be done with following code:
package asd;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class ImageAddingText {
public static void main(String args[]) throws IOException {
BufferedImage image = ImageIO.read(new File("C:\\Users\\Slobodan\\Desktop\\image2.png"));
Font font = new Font("Arial", Font.BOLD, 20);
Graphics g = image.getGraphics();
g.setFont(font);
g.setColor(Color.GREEN);
g.drawString("Medium", 50, 50);
System.out.println("Finished");
System.out.println(image.getWidth());
}
}
So image gets loaded into memory, image.getGraphics() create Graphics2D object, then the font, color and draw string are set.
But in the image nothing happens, it still remains completely unchanged.
The image is white and black, white occupying most of the space.. I tried to change colors, extension of the image, and seems nothing of that helps. I was expecting that i can see changes directly on the image, i thought it should work that way. After it runs and compiles, there are no error messages at all.
I am using Java 8 together with Spring Boot. (though i run only Java)
Does anyone maybe have an idea what can be the issue there?
Thank you very much for reading.
Upvotes: 0
Views: 1229
Reputation: 285403
Again, your code works for me, using an online image:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageAddingText {
public static void main(String args[]) throws IOException {
String imgUrl = "https://media.glamour.com/photos/5a425fd3b6bcee68da9f86f8/16:9/w_2560%2Cc_limit/best-face-oil.png";
// BufferedImage image = ImageIO.read(new File("C:\\Users\\Slobodan\\Desktop\\image2.png"));
URL url = new URL(imgUrl);
BufferedImage image = ImageIO.read(url);
// display the original image
Icon icon = new ImageIcon(image);
JOptionPane.showMessageDialog(null, icon);
Font font = new Font("Arial", Font.BOLD, 20);
Graphics g = image.getGraphics();
g.setFont(font);
g.setColor(Color.GREEN);
g.drawString("Medium", 50, 50);
g.dispose(); // you should always dispose resources *you* create yourself
// display the changed image
icon = new ImageIcon(image);
JOptionPane.showMessageDialog(null, icon);
System.out.println("Finished");
System.out.println(image.getWidth());
}
}
Upvotes: 1