Convert Text to Image using Java
Today, We are going to see how to convert a text into image using Java code. But before we proceed to code, We have to understand some of the classes used in this code.

BufferedImage – The BufferedImage subclass describes an Image with an accessible buffer of image data. This class extends image and implements WritableRenderedImage, Transparency.
BufferedImage Explanation

Font – Font class extends Object and Implements Serializable.  The Font class represents fonts, which are used to render text in a visible way
Font Details

FontMetrics – FontMetrics extends Object and Implements Serializable. The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen
FontMetrics Details

RenderingHints – The RenderingHints class defines and manages collections of keys and associated values
RenderingHints Details

Now lets us see an example code – Changing Text into an Image.

public class TexttoImage 
{
    
    public static void main(String[] args) throws Exception 
    {
        String text = "JavaInfinite";
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);// Represents an image with 8-bit RGBA color components packed into integer pixels.
        Graphics2D graphics2d = image.createGraphics();
        Font font = new Font("TimesNewRoman", Font.BOLD, 24);
        graphics2d.setFont(font);
        FontMetrics fontmetrics = graphics2d.getFontMetrics();
        int width = fontmetrics.stringWidth(text);
        int height = fontmetrics.getHeight();
        graphics2d.dispose();

        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        graphics2d = image.createGraphics();
        graphics2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        graphics2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        graphics2d.setFont(font);
        fontmetrics = graphics2d.getFontMetrics();
        graphics2d.setColor(Color.GREEN);
        graphics2d.drawString(text, 0, fontmetrics.getAscent());
        graphics2d.dispose();
        try {
            ImageIO.write(image, "png", new File("F:/Sample.jpg"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } 
}

Once you run the code,

op1

 

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *