I am trying to add a title string below a png image. The problem is that there is no space for the text and I have to add some white space. Im not sure how to do this. This is what I have done so far:
BufferedImage image = ImageIO.read(new File("output.png"));
Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(30f));
g.setColor(Color.BLACK);
g.drawString("Hello World!", 100, 350);
g.dispose();
ImageIO.write(image, "png", new File("test.png"));
To add white space to the bottom of a BufferedImage, you have to create a new BufferedImage and copy the image.
The 30 on the 3rd line is 30 pixels of white space. Substitute any number you wish to get the amount of white space you want.
Why not simply add the spacing you need to the new
BufferedImage
s height?Here is an example I made:
The real magic happens here:
The above method will allow you to pass in text, a reference to the image and the amount of spacing you want to add. It will than draw the string to the image within the specified space. The image is resized before passing it to the above method (
drawTextOnImage(..)
) via:Test.java: