Writes text to a BufferedImage-object in the lower right corner. - Java 2D Graphics

Java examples for 2D Graphics:Image

Description

Writes text to a BufferedImage-object in the lower right corner.

Demo Code


import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main{
    public static DImage writeToImage(DImage img, String text) {
        BufferedImage bImg = img.toBufferedImage();

        BufferedImage tagged = writeToImage(bImg, text);

        return new DImage(tagged);
    }//ww  w .  j  a v a  2s  .  co  m
    /**
     * Writes text to a BufferedImage-object in the lower right corner.
     * Used to write the name of the regex unto the image object.
     * @param image The image to write on.
     * @param textToWrite The text to write
     * @return A new BufferedImage, which has text written unto it.
     */
    private static BufferedImage writeToImage(BufferedImage image,
            String text) {
        Graphics2D g = image.createGraphics();
        g.setFont(new Font("Sans-Serif", Font.BOLD, 17));
        FontMetrics fm = g.getFontMetrics();
        int w = fm.stringWidth(text) + 10;
        int h = fm.getHeight() + 3;
        g.setColor(Color.WHITE);
        g.fillRect(0, image.getHeight() - h, w, h);
        g.setColor(Color.BLACK);
        g.drawString(text, 5, image.getHeight() - 6);
        g.dispose();
        return image;
    }
}

Related Tutorials