×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Massimo Zappino
Added: Jan 29, 2011 7:35 PM
Views: 242
  1. private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
  2.     {
  3.         // load image from filename
  4.         Image image = Toolkit.getDefaultToolkit().getImage(filename);
  5.         MediaTracker mediaTracker = new MediaTracker(new Container());
  6.         mediaTracker.addImage(image, 0);
  7.         mediaTracker.waitForID(0);
  8.         // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());
  9.  
  10.         // determine thumbnail size from WIDTH and HEIGHT
  11.         double thumbRatio = (double)thumbWidth / (double)thumbHeight;
  12.         int imageWidth = image.getWidth(null);
  13.         int imageHeight = image.getHeight(null);
  14.         double imageRatio = (double)imageWidth / (double)imageHeight;
  15.         if (thumbRatio < imageRatio) {
  16.             thumbHeight = (int)(thumbWidth / imageRatio);
  17.         } else {
  18.             thumbWidth = (int)(thumbHeight * imageRatio);
  19.         }
  20.  
  21.         // draw original image to thumbnail image object and
  22.         // scale it to the new size on-the-fly
  23.         BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
  24.         Graphics2D graphics2D = thumbImage.createGraphics();
  25.         graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  26.         graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
  27.  
  28.         // save thumbnail image to outFilename
  29.         BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
  30.         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  31.         JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
  32.         quality = Math.max(0, Math.min(quality, 100));
  33.         param.setQuality((float)quality / 100.0f, false);
  34.         encoder.setJPEGEncodeParam(param);
  35.         encoder.encode(thumbImage);
  36.         out.close();
  37.     }