3 Replies Latest reply: Jul 24, 2010 4:59 AM by 843802 RSS

    Creating Thumbnail from an Image with transparent background

    843802
      Hello,

      I want to create a thumbnail image of size 200 x 200 pixels from an image of any size.
      As the thumbnail is square, I'm centering the image according to size.

      The code I'm using is working fine BUT after centering and resizing original image
      and writing it to output file the remaining area is of black color.

      I want the background should be transparent.
      Code I'm using is not using JAI.
      Please suggest me the solution.

      the code I'm using is as follows:
      public static void makeThumbnail(String inFile, String thumbFile ) throws Exception {
      Image image = Toolkit.getDefaultToolkit().getImage(inFile);
      MediaTracker mediaTracker = new MediaTracker(new Container());
      mediaTracker.addImage(image, 0);
      mediaTracker.waitForID(0);
      int fixedHeight = 200 ;
      int fixedWidth = 200 ;
      int imageWidth = image.getWidth(null);
      int imageHeight = image.getHeight(null);
      double imageRatio = 0.25 ;      
      int thumbHeight = (int)(imageHeight * imageRatio );
      int thumbWidth = (int)(imageWidth * imageRatio );
      int x = ( fixedWidth - thumbWidth )/2 ;
      int y = ( fixedHeight - thumbHeight )/2 ;
      System.out.println(thumbHeight + " - " + y );
      System.out.println(thumbWidth + " - " + x );
      // draw original image to thumbnail image object and
      // scale it to the new size on-the-fly
      BufferedImage thumbImage = new BufferedImage(fixedWidth, fixedHeight, BufferedImage.TYPE_INT_RGB);
      Graphics2D graphics2D = thumbImage.createGraphics();
      graphics2D.setColor( new Color( 255, 255, 255, 0) );
      int rule = AlphaComposite.SRC_IN ;
      AlphaComposite ac = AlphaComposite.getInstance(rule, 0.9f);
      graphics2D.setComposite(ac);
      graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      graphics2D.drawImage(image, x, y, thumbWidth, thumbHeight, null);
      // save thumbnail image to OUTFILE
      BufferedOutputStream out = new BufferedOutputStream(new    FileOutputStream(thumbFile));
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
      int quality = 60 ;
      quality = Math.max(0, Math.min(quality, 100));
      param.setQuality((float)quality / 100.0f, false);
      encoder.setJPEGEncodeParam(param);
      encoder.encode(thumbImage);
      }