Saturday, December 11, 2010

Resize an image in Java

Given below is a reusable method in Java for image resizing. I’ll walk you through the code explaining what is done by each code line and will give for better understanding. for this method original image name with path and extension should be fed as an argument. Size of a side of the resized image is also required as an argument for this resizeImage method which returns the state of the image resizing action as a boolean.

public boolean resizeImage(String pathAndNameWithExtention, int sizeOfASideAfterResize){
        int size = sizeOfASideAfterResize;
        String name = pathAndNameWithExtention;
        //format name
        String path = "";
        String nameTxt = "";
        String ext = "";
        if(name!=null){
            //get path
            int tempIndex1 = name.lastIndexOf("\\");
            int tempIndex2 = name.lastIndexOf("/");
            if(tempIndex1==-1 && tempIndex2!=-1){
                path = name.substring(0, tempIndex2);
            }else if(tempIndex1!=-1 && tempIndex2==-1){
                path = name.substring(0, tempIndex1);
            }else if(tempIndex1!=-1 && tempIndex2!=-1){
                if(tempIndex1>tempIndex2){
                    path = name.substring(0, tempIndex1);
                }else{
                    path = name.substring(0, tempIndex2);
                }
            }else{
                System.out.println("ERROR! Path Information is wrong.");
                return false;
            }
            //get name
            int tempIndex3 = name.lastIndexOf(".");
            if(tempIndex3!=-1){
                nameTxt = name.substring(path.length(), tempIndex3);
                ext = name.substring(tempIndex3+1);
            }else{
                System.out.println("ERROR! Image name extension is wrong.");
                return false;
            }
        }
        //read original image
        BufferedImage originalImg;
        try {
            originalImg= ImageIO.read(new File(name));
            //get original image width and height
            int width = originalImg.getWidth(null);
            int height = originalImg.getHeight(null);

            //calculate resized width and height to avoid distortion
            if(width>height){
                height = (int)(((float)height/(float)width)*size);
                width = size;
            }else{
                width= (int)(((float)width/(float)height)*size);
                height= size;
            }
            boolean flag = false;
            //create the resized Image
            BufferedImage resizedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = resizedImg.getGraphics();
            flag = g.drawImage(originalImg, 0, 0, width, height, Color.WHITE, null);
            //save the image
            File outFile = new File(path+"/"+nameTxt+"_resized."+ext);
            ImageIO.write(resizedImg, ext, outFile);
            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

Majority of the code lines has been devoted to retrieve the image path, name text and the extension of the image name argument of this method. Then the original image is retrieved using the given parameters to a BufferedImage by using ImageIO.read Please note that this image read needs to be handled within a try-catch as given in above complete code.

BufferedImage originalImg= ImageIO.read(new File(name));

Then a small calculation is performed to get the resized image dimensions, by considering the original image width, height and required size of the resized image to avoid distortion. Code segment that follows this calculation is as follows,

if(width>height){
    height = (int)(((float)height/(float)width)*size);
    width = size;
}else{
     width= (int)(((float)width/(float)height)*size);
     height= size;
}

Then the image is redrawn to the calculated width and height as follows by using the Graphic class of Java. Color given in the drawImage method is the background color of the drawn image.

BufferedImage resizedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = resizedImg.getGraphics();
flag = g.drawImage(originalImg, 0, 0, width, height, Color.BLACK, null);

Finally the resized image is written back to the read location with a modified file name as “<name>_resized.<extension>” using ImageIO.write method.

The Java packages that need to be imported for this method to work are as follows,

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

To test this method I have created a new class named Test and included the above resizeImage method and the below main method to it.

public static void main(String[] arg){
        Test t = new Test();
        boolean b = t.resizeImage("F:\\testFolder\\TestImage.jpg", 300);
        System.out.println(b);
}

Running this Test class results in creating a new image named TestImage_resized.jpg with max side size of 300px in “F:\testFolder”.

No comments:

Post a Comment