I use what I think is somewhat of an outdated method (in an ImageUtils class):
Code:
public void createThumb(HttpServletRequest request, File thumbFile, File savedFile)
{
try
{
// load image from the savedFile (the original jpeg uploaded)
Image image = Toolkit.getDefaultToolkit().getImage(savedFile.toURL());
// MediaTracker to track the status of media objects
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 1);
mediaTracker.waitForID(1);
logger.info("### mediatracker done");
// set the thumbnail's width and height
int thumbWidth = 125;
int thumbHeight = 125;
// sets ratio of widht to height
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
// get the width and height of the original image
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
// get the ratio of the original image
double imageRatio = (double)imageWidth / (double)imageHeight;
// set the height or width to preserve the ratio of the original image
if (thumbRatio < imageRatio)
{
thumbHeight = (int)(thumbWidth / imageRatio);
}else{
thumbWidth = (int)(thumbHeight * imageRatio);
}
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage thumbImage = new BufferedImage(thumbWidth,
thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
logger.info("### image drawn");
// save thumbnail image to thumbFile
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(thumbFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
// set the quality of the thumb (100 being full quality)
int quality = 100;
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
// close the output stream after it is saved
out.close();
}catch(Exception e){
logger.info("### Exception " + e);
}
}
I got that from the Sun website quite awhile ago... I think there are more modern ways to do it, but this works for me.
Like Costin warns, if there is an error, you can end up with some space garbage on your server. In my case, pictures are uploaded with other information... if there is an error (random file), then the admin will go back to the form and see the errors and make those corrections, the random file gets overwritten then.
Good luck!
Steve O