/ Published in: Java
Create Thumbnail of an image in Java
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
{ // load image from filename mediaTracker.addImage(image, 0); mediaTracker.waitForID(0); // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny()); // determine thumbnail size from WIDTH and HEIGHT double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; 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 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // save thumbnail image to outFilename JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); param.setQuality((float)quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); }