Generate Thumbnail and Display to Browser from a Servlet
843840Apr 3 2002 — edited Apr 4 2002I have the following code working locally generating a thumbnail jpeg to the file system.
My question is how would I do the same in a servlet and display the results to the browser?
I don't necessarily want to save the thumbnail to the filesystem on the server, if I can get
away with it. To sum up, using a servlet I would like to reference a full size image (jpeg) on the filesystem and dynamically build a thumbnail in memory and display in via the browser. Can this be done? Help would be greatly appreciated.
import java.awt.* ;
import java.awt.image.* ;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.* ;
import java.net.*;
import javax.swing.*;
import com.sun.image.codec.jpeg.* ;
public class GenerateThumbnail {
public static void main (String args[]) {
try {
// Load normal-sized file
InputStream in = new FileInputStream("test.jpg");
JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(in);
BufferedImage inImg = dec.decodeAsBufferedImage();
// Scale down to half the size
AffineTransform xform = AffineTransform.getScaleInstance(0.3,0.3);
AffineTransformOp xformOp = new AffineTransformOp(xform,AffineTransformOp.TYPE_BILINEAR);
BufferedImage outImg = new BufferedImage(150,112, BufferedImage.TYPE_INT_RGB);
xformOp.filter(inImg, outImg);
// encode the reduced image
OutputStream out = new FileOutputStream("thumbnail.jpg");
JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
enc.encode(outImg);
in.close();
out.close();
}
catch (IOException ie) {}
}
}