Tuesday, January 24, 2012

Resizing Images in Java. Creating thumbnails

In this article we will find out how to create thumbnails from images with Java. Thumbnails are used everywhere on web e.g. eshop product catalogue, image galleries etc.  So what does Java offer to a developer?  We can use standard Java libraries or imgscalr library for this.


Standard libraries


Java provides AWT framework and ImageIO library as a standard tool for processing images.

1. First we need to load image from a file using ImageIO.read() method.

File sourceImageFile = new File("bigfile.jpg");
BufferedImage img = ImageIO.read(sourceImageFile);

2. Then we resize the image by calling getScaledInstance()

Image scaledImg = img.getScaledInstance(100, 50, Image.SCALE_SMOOTH);

3. Create a new image with desired dimension and draw it

BufferedImage thumbnail = new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB);
thumbnail.createGraphics().drawImage(scaledImg,0,0,null);

4. Write to file

ImageIO.write(thumbnail, "jpg", new File("thumbnail.jpg"));

5. Or you can get the image as an array of bytes

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(thumbnail, "jpg", baos);
baos.flush();
byte[] imageBytes = baos.toByteArray();

That is all. The only downside of this approach is speed and quality.


Better scalling results can be archieved with imgscalr library


Imgscalr

From the description of imgscalr:

imgscalr is an very simple and efficient (hardware accelerated) “best-practices” image-scaling library implemented in pure Java 2D; as of the 4.0 release imgscalr now includes a handful of other convenience image operations, all as easy to use as resize.

Maven dependency

  <dependency>
    <groupId>org.imgscalr</groupId>
    <artifactId>imgscalr-lib</artifactId>
    <version>4.2</version>
  </dependency>


Usage

BufferedImage sourceImage =ImageIO.read(...);

BufferedImage scaledImg = Scalr.resize(sourceImage, Method.SPEED, Scalr.Mode.AUTOMATIC, 100, 50, Scalr.OP_ANTIALIAS);

Method: AUTOMATIC, SPEED, QUALITY, ...
Mode: AUTOMATIC, FIT_EXACT, FIT_TO_HEIGHT, FIT_TO_WIDTH, ...
Options: OP_ANTIALIAS, OP_BRIGHTER, OP_DARKER, ...


1 comment: