I have an image on top of which I would like to write text that has multiple lines, is center-aligned, and dynamic (variable width). I've tried using the drawString
method from Graphics
, but I could not get the centering and dynamic positioning to work. I'm currently poking around in the swing
library with JLabels
and such, but I'm having difficulty with finding a relatively simple approach to this. I would also like to have the final image written to a file, but it seems that mixing ImageIO
with JPanel
s is not working very well.. I'm getting just a black box at the moment.. If anyone could provide even a simple outline of how to approach this, I would greatly appreciate that.
Thank you!
Sorry, I should have been more specific.. I would like the text itself to be center-aligned (as in the middle of each row should line up), rather than having the text be placed in the center of the image. The text will be placed in some other location on the image, not in the middle. Again, I apologize for the unclear descriptions. Thanks!
You don't really need swing at all if you just want to generate image files.
You can do something like this:
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
BufferedImage img = ImageIO.read(new File("dog.jpg")); // try/catch IOException
int width = img.getWidth();
int height = img.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();
// draw graphics
g2d.drawImage(img, 0, 0, null);
g2d.drawString(text, x, y);
g2d.dispose();
try {
// Save as PNG
File file = new File("newimage.png");
ImageIO.write(bufferedImage, "png", file);
// Save as JPEG
file = new File("newimage.jpg");
ImageIO.write(bufferedImage, "jpg", file);
} catch (IOException e) { }
For more info, see:
http://www.exampledepot.com/egs/javax.imageio/Graphic2File.html
The text alignment and centering can be done using the FontMetrics class.
You should use a drawString()
.
To properly center a text you need to calculate the width for a given font:
Font font = getFont();
FontMetrics metrics = getFontMetrics( font );
int width = metrics.stringWidth( theString );
And remember to add -Djava.awt.headless=true
if you want to call in on server (without GUI).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With