Wednesday, March 30, 2011

Resize an image in Java - Any Open Source Library ?

I need to resize PNG, JPeg and Gif files. Are there good java open source libraries to do that ?

From stackoverflow
  • After loading the image you can try:

    BufferedImage createResizedCopy(Image originalImage, 
          int scaledWidth, int scaledHeight, 
          boolean preserveAlpha)
        {
         System.out.println("resizing...");
         int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
         BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
         Graphics2D g = scaledBI.createGraphics();
         if (preserveAlpha) {
          g.setComposite(AlphaComposite.Src);
         }
         g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); 
         g.dispose();
         return scaledBI;
        }
    
    Carl Manaster : Thank you! This is exactly what I needed right now, and it works great.
    morgancodes : I found this technique creates an image which isn't high-enough quality for my needs.
  • Java Advanced Imaging is now open source, and provides the operations you need.

  • If you are dealing with large images or want a nice looking result it's not a trivial task in java. Simply doing it via a rescale op via Graphics2D will not create a high quality thumbnail. You can do it using JAI, but it requires more work than you would imagine to get something that looks good and JAI has a nasty habit of blowing our your JVM with OutOfMemory errors.

    I suggest using ImageMagick as an external executable if you can get away with it. Its simple to use and it does the job right so that you don't have to.

  • You don't need a library to do this. You can do it with Java itself.

    Chris Campbell has an excellent and detailed write-up on scaling images - see this article.

    Chet Haase and Romain Guy also have a detailed and very informative write-up of image scaling in their book, Filthy Rich Clients.

  • If, having imagemagick installed on your maschine is an option, I recommend im4java. It is a very thin abstraction layer upon the command line interface, but does its job very well.

0 comments:

Post a Comment