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”.

Java Tips

How to Center the JFrame/JDialog in the screen

In the JFrame/JDialog initialize method add the following code lines along with the correct dimensions of your container instead of values 300, 200.

private void initialize() {
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (dim.width - 300)/2;
        int y = (dim.height - 200)/2;
        this.setLocation(x, y);
        this.setSize(300, 200);
        ……
}

In the first line it gets the Screen Size to a variable named dim. Please note that the example container’s width is 300px and height is 200px. Using these values we can calculate the x, y positions for the container to appear in the center of the screen. Then the calculated x, y values are fed to the component using setLocation method while dimensions of the container is fed using setSize method inside initialize method of the container.

 

How to get the working directory in java

It is a quite simple, yet very useful feature provided by Java.

System.getProperty("user.dir");

This will return the current working directory as a string and comes very handy to define relative paths inside Java programs.

 

How to add an image to a Java container

This can be achieved by adding a new label with the required image’s size, to the container and setting the label’s icon to point the image that is required to be added to the container.

private JPanel getJContentPane() {
        if (jContentPane == null) {
            lbl_Img = new JLabel();
            lbl_Img.setBounds(new Rectangle(101, 9, 164, 16));
            lbl_Img.setIcon(new ImageIcon(System.getProperty("user.dir")+"/icons/edit.png"));
            ……
        }
        ……
}

This code will display  the ‘edit.png’ image in the icons folder of the working directory of the program. Please note that if the image is lager than the label bounds, this will display only the upper left corner of the image to the extent of the defined label bounds. Please refer the “Resize a given image in Java” blog entry to learn how to resize an image in java.