tags:

views:

1050

answers:

4

Can someone please help with some code for creating a thumbnail for a JPEG in Java.

I'm new at this, so a step by step explanation would be appreciated.

+5  A: 
Image img = ImageIO.read(new File("test.jpg")).getScaledInstance(100, 100, BufferedImage.SCALE_SMOOTH);

This will create a 100x100 pixels thumbnail as an Image object. If you want to write it back to disk simply convert the code to this:

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
img.createGraphics().drawImage(ImageIO.read(new File("test.jpg")).getScaledInstance(100, 100, Image.SCALE_SMOOTH),0,0,null);
ImageIO.write(img, "jpg", new File("test_thumb.jpg"));

Also if you are concerned about speed issues (the method described above is rather slow if you want to scale many images) use these methods and the following declaration :

private BufferedImage scale(BufferedImage source,double ratio) {
  int w = (int) (source.getWidth() * ratio);
  int h = (int) (source.getHeight() * ratio);
  BufferedImage bi = getCompatibleImage(w, h);
  Graphics2D g2d = bi.createGraphics();
  double xScale = (double) w / source.getWidth();
  double yScale = (double) h / source.getHeight();
  AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
  g2d.drawRenderedImage(source, at);
  g2d.dispose();
  return bi;
}

private BufferedImage getCompatibleImage(int w, int h) {
  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice gd = ge.getDefaultScreenDevice();
  GraphicsConfiguration gc = gd.getDefaultConfiguration();
  BufferedImage image = gc.createCompatibleImage(w, h);
  return image;
}

And then call :

BufferedImage scaled = scale(img,0.5);

where 0.5 is the scale ratio and img is a BufferedImage containing the normal-sized image.

Savvas Dalkitsis
+1  A: 

The JMagick library (and implementation of ImageMagick in Java) will have what you need.

mfloryan
+1 and give much much better output results
Boris Pavlović
A: 

thanx guy u've been big help

:D you should post this in a comment btw not as an answer. Also you should denote the correct answer by clicking on the tick and maybe vote the correct answer up.
Savvas Dalkitsis
+1  A: 

the Java code above (with the scale / getCompatibleImage methods) worked great for me, but when I deployed to a server, it stopped working, because the server had no display associated with it -- anyone else with this problem can fix it by using: BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

instead of BufferedImage bi = getCompatibleImage(w, h);

and deleting the getCompatibleImage method

(later note -- it turns out this works great for most images, but I got a bunch from my companys marketing department that are 32 bit color depth jpeg images, and the library throws an unsupported image format exception for all of those :( -- imagemagick / jmagick are starting to look more appealing)