import java.awt.*; import java.awt.image.*; import javax.imageio.*; import javax.imageio.stream.*; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /* * This servlet provides the service of labeling an * image with a text string. The caller of the * servlet gets to specify the image (local file or * URL), the text string, text size, and the color. * This servlet has a large number of limitations, * the foremost being that it will only write JPEG * images (with minimal compression). *

* Note: on X-based systems like Linux or Solaris, * this servlet probably won't work unless the host * is running an X server. *

* This servlet requires the JAI/IIO package to be * installed to perform JPG image output. *

* Example img src URL:
* http://www.myhost.com/servlet/ImageLabelServer?src=http://www.foobar.com/logo.jpg&text=Foobar+Logo&size=28&color=90f000ff *
* This sample will cause the servlet to got retrieve the image logo.jpg from * the www.foobar.com web site, and then overlay the text "Foobar Logo" in * partially transparent purple 28-point text. * * @author Neal Ziring */ public class ImageLabelServlet extends HttpServlet { public static final String PARM_IMAGE = "src"; public static final String PARM_TEXT = "text"; public static final String PARM_SIZE = "size"; public static final String PARM_COLOR= "color"; public static final String IMG_OUT_SUFFIX = "jpg"; public static final String IMG_OUT_MIME = "image/jpeg"; /* need these for doing AWT stuff */ static Component ob = null; static Toolkit tk = null; /** * Initialize stuff we need for this servlet. */ public void init(ServletConfig conf) { if (tk == null) tk = Toolkit.getDefaultToolkit(); if (ob == null) { ob = new Frame(); ob.addNotify(); } } /** * Just call the doGet method to handles posts. */ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { doGet(req,resp); } /** * Process a request - we look for the parameters * listed above. Our output consists of an image * in image/jpeg format, or a 404 message if we * couldn't load the requested image. */ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { String src = req.getParameter(PARM_IMAGE); if (src == null || src.length() == 0) { resp.sendError(resp.SC_BAD_REQUEST, "No source image specified"); return; } String text = req.getParameter(PARM_TEXT); if (text == null || text.length() == 0) text = (new Date()).toString(); String size = req.getParameter(PARM_SIZE); int textSize = 14; try { textSize = Integer.parseInt(size); } catch (Exception ie) { } String color = req.getParameter(PARM_COLOR); int textColor = 0x666666; try { if (color.startsWith("#")) color = color.substring(1); textColor = (int)(Long.parseLong(color, 16) & 0x0ffffffff); } catch (Exception ie2) { } float cq = 0.01F; String qual = req.getParameter("q"); if (qual != null && qual.length() > 0) { try { cq = (float)(Double.parseDouble(qual)); } catch (Exception ie) { } } Font f = new Font("Sans-serif", Font.BOLD, textSize); Image img = null; if (src.indexOf('/') >= 0 || src.indexOf(':') >= 0) { try { URL u = new URL(src); img = tk.createImage(u); } catch (Exception ie3) { } } else { try { img = tk.createImage(src); } catch (Exception ie4) { } } MediaTracker mt = new MediaTracker(ob); mt.addImage(img, 2); try { mt.waitForID(2); } catch (InterruptedException eix) { } if (mt.isErrorID(2)) img = null; if (img == null) { resp.sendError(resp.SC_NOT_FOUND, "Could not load source image"); } int w, h; w = img.getWidth(ob); h = img.getHeight(ob); BufferedImage img2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); if (img2 == null) System.err.println("img2 is Null!"); Graphics g = img2.getGraphics(); if (g == null) System.err.println("Graphics is Null!"); Color c = new Color(textColor, (((textColor >> 24) & 0xff) != 0)); g.setColor(c); g.setFont(f); g.drawImage(img, 0, 0, ob); g.drawString(text, textSize/2, (textSize * 5)/4); img.flush(); img = null; Iterator writers = ImageIO.getImageWritersBySuffix(IMG_OUT_SUFFIX); if (!(writers.hasNext())) { resp.sendError(resp.SC_CONFLICT, "Cannot write JPEG image!"); return; } if (!writeImageOut((ImageWriter)(writers.next()), img2, resp, cq)) { resp.sendError(resp.SC_CONFLICT, "Writing image failed"); return; } img2.flush(); img2 = null; return; } /** * Write out the image to the servlet response stream. * This method always sends a mime type of IMG_OUT_MIME. */ boolean writeImageOut(ImageWriter wr, BufferedImage img, HttpServletResponse resp, float cq) { boolean ret = false; resp.setContentType(IMG_OUT_MIME); try { OutputStream oos = resp.getOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(oos); wr.setOutput(ios); ImageWriteParam parm = wr.getDefaultWriteParam(); parm.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); parm.setCompressionQuality(cq); cq = parm.getCompressionQuality(); IIOImage ii = new IIOImage(img, null, null); wr.prepareWriteSequence(null); wr.writeToSequence(ii, parm); wr.endWriteSequence(); ios.flush(); wr.dispose(); ios.close(); ret = true; } catch ( Exception ioe) { System.err.println("Error in image writing: " + ioe); ioe.printStackTrace(); } return ret; } }