the matt jones website.‎ > ‎Java‎ > ‎

Convert text to an image

Below is the Java source code I (have) use(d) (in the past) to create an image from an E-mail. Basically this little bit of code prints a background, and some text onto a image and writes it to a file as a png. This is useful in all sorts of situations, and I believe from this code below you could make all sorts of variations to suit your needs. If you have any questions, please email me. Below is a sample of the type of image it produces. This program will create an image out of text in Java.

Usage: textToImage.jar email fg-colour-hex bg-colour-hex filename
Example: java -jar textToImage.jar FFFFFF 0000FF C:\dir\image.png

You can download the Jar (in the attachments), the Netbeans Project (in the attachments) or use the code below for your own use. I don't care if you refer to me in anyway or not if you use this code below. It's not like I can stop you or afford an expensive copyright lawsuit or anything.

package emailToImage;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import javax.imageio.ImageIO;

 * @author Matthew Jones, 2009
public class Main {

    public static void main(String[] args) throws IOException {
        try {

            // collect correct inputs or DIE.
            String email = args[0];
            Color fg = new Color(Integer.parseInt(args[1], 16));
            Color bg = new Color(Integer.parseInt(args[2], 16));
            String filename = args[3];

            // call render image method.
            RenderedImage rendImage = writeImage(email, fg, bg);

            File file = new File(filename);

            ImageIO.write(rendImage, "png", file);

        } catch (Exception e) {
            // Sloppy Error handling below
            System.out.println("Usage: textToImage.jar email fg-colour-hex bg-colour-hex filename");
            System.out.println("Example: textToImage.jar FFFFFF 0000FF C:\\dir\\image.png");

    private static RenderedImage writeImage(String text, Color fgc, Color bgc) {

        // calculate image size requirements.
        int width = (text.length() * 7) + 5;

        // standard height requirement of 16 px.
        int height = 16;
        BufferedImage buffRenderImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D flatGraphic = buffRenderImage.createGraphics();

        // Draw background
        flatGraphic.fillRect(0, 0, width, height);

        //Draw text
        Font font = new Font("Courier", Font.BOLD, 12);
        flatGraphic.drawString(text, 1, 10);

        // don't use drawn graphic anymore.

        return buffRenderImage;

Matthew Jones,
15 Oct 2009, 19:20
Matthew Jones,
15 Oct 2009, 19:19