FileDocCategorySizeDatePackage
ShrinkFilter.javaAPI DocExample2228Tue Jan 25 10:45:14 GMT 2000None

ShrinkFilter

public class ShrinkFilter extends HttpServlet

Fields Summary
Constructors Summary
Methods Summary
public voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

    ServletOutputStream out = res.getOutputStream();

    String contentType = req.getContentType();
    if (contentType == null || !contentType.startsWith("image")) {
      throw new ServletException("Incoming content type must be \"image/*\"");
    }

    // Fetch the bytes of the incoming image
    DataInputStream in = new DataInputStream(
                         new BufferedInputStream(
                         req.getInputStream()));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[4 * 1024];  // 4K buffer
    int len;
    while ((len = in.read(buf, 0, buf.length)) != -1) {
      baos.write(buf, 0, len);
    }

    // Create an image out of them
    Image image = Toolkit.getDefaultToolkit()
                            .createImage(baos.toByteArray());

    // Construct an unshown frame
    // No addNotify() since it's peer isn't needed
    Frame frame = new Frame();

    // Load the image, so we can get a true width and height
    MediaTracker mt = new MediaTracker(frame);
    mt.addImage(image, 0);
    try {
      mt.waitForAll();
    }
    catch (InterruptedException e) {
      getServletContext().log(e, "Interrupted while loading image");
      throw new ServletException(e.getMessage());
    }

    // Shrink the image to half its width and half its height.
    // An improved version of this servlet would receive the desired
    // ratios in its init parameters.
    // We could also resize using ReplicateScaleFilter or 
    // AreaAveragingScaleFilter.
    Image shrunk = image.getScaledInstance(image.getWidth(frame) / 2,
                                           image.getHeight(frame) / 2,
                                           image.SCALE_DEFAULT);

    // Encode and return the shrunken image
    res.setContentType("image/gif");
    GifEncoder encoder = new GifEncoder(shrunk, out);
    encoder.encode();