How to Create ThumbNail Images In Java

Posted on the 09 September 2013 by Abhishek Somani @somaniabhi
You can do image resizing in java by using imgscalr . You can create thumbnails easily , by providing desired width and height . Here is the Pom Dependency for imgscalr :
<dependency>
    <groupId>org.imgscalr</groupId>
    <artifactId>imgscalr-lib</artifactId>
    <version>4.2</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>

Or, you can download it with this link . Here is the sample java program to convert an image into 50*50 thumbnail .
package com.datamigration.main;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;

/**
 * 
 * 
 * @author Abhishek Somani
 * 
 */
public class ThumbnailExample {
 
 
 public static void main(String[] args) throws IOException {
  
  long startTime = System.currentTimeMillis();
  File f = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg");
  BufferedImage img = ImageIO.read(f); // load image

  //Quality indicate that the scaling implementation should do everything
   // create as nice of a result as possible , other options like speed
   // will return result as fast as possible
//Automatic mode will calculate the resultant dimensions according
//to image orientation .so resultant image may be size of 50*36.if you want
//fixed size like 50*50 then use FIT_EXACT
//other modes like FIT_TO_WIDTH..etc also available.

  BufferedImage thumbImg = Scalr.resize(img, Method.QUALITY,Mode.AUTOMATIC, 
             50,
                   50, Scalr.OP_ANTIALIAS);
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  ImageIO.write(scaledImg,"jpg",os);
  
  
  
  
  File f2 = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum_thumb.jpg");
  
  
  ImageIO.write(scaledImg, "jpg", f2);
  
  System.out.println("time is : " +(System.currentTimeMillis()-startTime));
  
  ByteArrayOutputStream thumbOs = new ByteArrayOutputStream();
  ImageIO.write(thumbImg,"jpg",thumbOs);
  
 }

}


Post Comments and Suggestions !!