Search This Blog

Tuesday, January 20, 2009

text-image-generator example

As a follow-up on my previous post, here is an example of how to use the text-image generation library. Consider the following code:

TextImage testImage = new TextImageImpl(400, 250, new Margin(0, -5));

// Declare or read the fonts you need
Font header = new Font("Sans-Serif", Font.BOLD, 15);
Font plain = new Font("Sans-Serif", Font.PLAIN, 12);

// Read in any images you need
InputStream is = Test.class.getResourceAsStream("/warning.jpg");
Image warning =;
// Put close() in try-finally block with production code!

// 1. specify font and write text with a newline
testImage.useFont(header).writeLine("Example usage text-image-generator.").newLine();
// 2. enabled the wrapping of text and write text which is automatically wrapped
testImage.useFont(plain).wrap(true).write("This is an example of how to use the text-image generation library. With this library you can dynamically generated textbased content as images (png or jpeg). Notice how this sentence is automatically wrapped. See the code at for more examples.").newLine();

// 3. Disable text-wrapping again. Write underlined text.
testImage.wrap(false).useColor(Color.BLUE).useFontStyle(Style.UNDERLINED).write("This line of text is underlinedand blue.").useFontStyle(Style.PLAIN).newLine();
testImage.writeLine("You can also embed images in your generated image:");
// 4. embed the actual image. Here we use absolute positioning
testImage.write(warning, 175, 175);

// 5. Write the image as a png to a file
OutputStream os = new FileOutputStream(new File("example.png"));

The code above generates the following image:

The text-image generation code can be downloaded at Here you will find more examples of how to use this library. Hope you enjoy.
Post a Comment