Posted By

roizaig on 04/20/13


Tagged

image thumbnail


Versions (?)

Create Thumbnail of an image in Java


 / Published in: Java
 

Create Thumbnail of an image in Java

  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. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  30. JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
  31. quality = Math.max(0, Math.min(quality, 100));
  32. param.setQuality((float)quality / 100.0f, false);
  33. encoder.setJPEGEncodeParam(param);
  34. encoder.encode(thumbImage);
  35. out.close();
  36. }

Report this snippet  

You need to login to post a comment.