// TextToJpeg.java - creates a JPEG image to display text in a crawler-safe fashion // By Rowland http://rowland.blcss.com/ import java.awt.*; import java.awt.font.*; import java.awt.geom.*; import java.awt.image.*; import java.io.*; import com.sun.image.codec.jpeg.*; class TextToJpeg { public Color bgcolor= Color.white; public Color fgcolor= Color.black; public int fontsize= 14; public int fontstyle= Font.PLAIN; public String fontname = "Arial"; public String text= "???"; public TextToJpeg() { } public TextToJpeg(Color _bgcolor, Color _fgcolor, int _fontsize) { bgcolor= _bgcolor; fgcolor= _fgcolor; fontsize= _fontsize; } public BufferedImage getBufferedImage(String _text) { text= _text; return getBufferedImage(); } public BufferedImage getBufferedImage() { FontMetrics fm; BufferedImage img = new BufferedImage(1000, 200, BufferedImage.TYPE_INT_RGB); // ...big canvas because we don't know how big we'll need Graphics2D g2 = img.createGraphics(); g2.setBackground(bgcolor); g2.clearRect(0,0, 1000,200); g2.setColor(fgcolor); Font font = new Font(fontname, fontstyle, fontsize); g2.setFont(font); fm= g2.getFontMetrics(); float ascent= fm.getAscent(); FontRenderContext frc= g2.getFontRenderContext(); TextLayout tl = new TextLayout(text, font, frc); float descent= tl.getDescent(); float advance= tl.getAdvance(); tl.draw(g2, 0.0f, (float)ascent); // Now extract the part we want... BufferedImage img2= img.getSubimage(0, 0, (int)advance, (int)(ascent+descent)); g2.dispose(); return img2; } public void jpegEncode(OutputStream out, String _text) throws IOException { text= _text; jpegEncode(out); } public void jpegEncode(OutputStream out) throws IOException { BufferedImage img= getBufferedImage(); JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img); param.setQuality(1.0f, true); encoder.encode(img, param); } public void jpegEncodeToFile(String _text, String filespec) throws IOException { jpegEncodeToFile(_text, new File(filespec)); } public void jpegEncodeToFile(String filespec) throws IOException { jpegEncodeToFile(new File(filespec)); } public void jpegEncodeToFile(String _text, File f) throws IOException{ text= _text; jpegEncodeToFile(f); } public void jpegEncodeToFile(File f) throws IOException { FileOutputStream fout= new FileOutputStream(f); jpegEncode(fout); fout.close(); } public static void main(String args[]) { try { TextToJpeg t2j= new TextToJpeg(); t2j.text= args[0]; t2j.jpegEncodeToFile(args[1]); } catch (Exception E) { System.err.println(E.toString()); } } }