views:

7266

answers:

5

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

+12  A: 

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;
    }
Burkhard
Thank you! This is exactly what I needed right now, and it works great.
Carl Manaster
I found this technique creates an image which isn't high-enough quality for my needs.
morgancodes
+3  A: 

Java Advanced Imaging is now open source, and provides the operations you need.

Ken Gentle
+3  A: 

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.

Joel Carranza
+2  A: 

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.

David
+1  A: 

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.

naltatis