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>
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.