Java Version

The two Java-based processors use the same code; the stylesheet simply uses the Saxon and Xalan conventions to identify the extension class. The extension function takes as its input the secret word, the name of the created JPEG file, the font size for the text, and the width and height of the JPEG file. Given those parameters, the code chooses a font at random and creates a blank canvas of the requested size. The Java code then checks to make sure the selected font exists (because Java runs on so many non-Windows platforms, we need to make sure). Once the font is set, we measure the dimensions of the secret word written in the font at the requested font size. If the word is too wide to fit into the graphic, we reduce the font size by 2 points until the word fits inside the canvas.

Once the font and font size are set, we draw the word on the canvas and finish by drawing random lines over the text. When we’ve drawn everything on the canvas, a couple of lines of Java code write the canvas out to a JPEG file. The last few lines of code here handle any exceptions that might occur. Here’s the complete listing:

/*
 * HiddenWord.java
 */ package com.oreilly.xslt; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.font.LineMetrics; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.FileOutputStream; ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.