Java Resize Image

Filed Under: Java

Today we will look into java resize image program. Recently I had to upload a lot of images to an FTP server but the images size were huge. Since I was going to use them only on web pages, it was wise to resize them to a smaller size and then upload it.

A few days back I provided a list of online tools to reduce image size. But when you have hundreds of images, it’s better to invest some time and write a program that does this work for you. So let’s see how we can resize an image in java.

Java Resize Image

We can use java.awt.Graphics2D class to resize image in java.

Below is the program that searches all the files in a directory and resizes them to the given size and saves it to a different directory.

The sample program here saves images in both PNG and JPG format but you can easily change it to serve your specific requirement.

Java Image Resize Program


package com.journaldev.util;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
/**
 * This class will resize all the images in a given folder
 * @author pankaj
 *
 */
public class JavaImageResizer {

	public static void main(String[] args) throws IOException {

		File folder = new File("/Users/pankaj/Desktop/images");
	    File[] listOfFiles = folder.listFiles();
		System.out.println("Total No of Files:"+listOfFiles.length);
		Image img = null;
		BufferedImage tempPNG = null;
		BufferedImage tempJPG = null;
		File newFilePNG = null;
		File newFileJPG = null;
		for (int i = 0; i < listOfFiles.length; i++) {
		      if (listOfFiles[i].isFile()) {
		        System.out.println("File " + listOfFiles[i].getName());
		        img = ImageIO.read(new File("/Users/pankaj/Desktop/images/"+listOfFiles[i].getName()));
		        tempPNG = resizeImage(img, 100, 100);
		        tempJPG = resizeImage(img, 100, 100);
		        newFilePNG = new File("/Users/pankaj/Desktop/images/resize/"+listOfFiles[i].getName()+"_New.png");
		        newFileJPG = new File("/Users/pankaj/Desktop/images/resize/"+listOfFiles[i].getName()+"_New.jpg");
		        ImageIO.write(tempPNG, "png", newFilePNG);
		        ImageIO.write(tempJPG, "jpg", newFileJPG);
		      }
		}
		System.out.println("DONE");
	}

	/**
	 * This function resize the image file and returns the BufferedImage object that can be saved to file system.
	 */
	public static BufferedImage resizeImage(final Image image, int width, int height) {
        final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        final Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.setComposite(AlphaComposite.Src);
        //below three lines are for RenderingHints for better image quality at cost of higher processing time
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.drawImage(image, 0, 0, width, height, null);
        graphics2D.dispose();
        return bufferedImage;
    }
}
  • First few lines uses Java IO to retrieve the list of files from the directory and then in the for loop, each file is processed.
  • resizeImage is the method where Graphics2D is used to resize image and return it as BufferedImage object.
  • Again we use ImageIO to write it into the file system in both PNG and JPG format.

Java Resize Image Important Points

  1. You can use RenderingHints to get high quality image at the cost of processing time. If you are not reducing images to a very small size, you might want to avoid them for faster processing. It depends on your situation that you need fast processing or better quality.
  2. The method doesn’t throw any Exception even if there are any files that are not image file like text, doc or pdf files. In that case, it will resize it and you will get a black colored image. You can easily extend the code to skip these files by filtering through their name.
  3. PNG image size is more than JPG image size for same resolution and it’s significant. So if you want to resize the image for web pages, you might want to use JPG format to save page loading time.

Java Image Resizer Program Results

I placed one PNG and one PDF file in the image directory and executed the program.

Input image is Eclipse Juno image of size 168KB:

Java Resize Image Example

Here are the output images with size:

java image resize output

PNG image without Hints 23KB

image resize java program

JPG image without Hints 4KB

java image resize Graphics2D

PNG image with Hints 24KB

image resize java program

JPG image with Hints 4KB

error image resize java program

Non image file output in PNG and JPG


 

 

 

 

I hope the given program help you in resizing images quickly.

Java Resize Image with Aspect Ratio

In a normal scenario, you want to keep the image aspect ratio else it will look stretched from one side. Here is the code snippet that will help you in maintaining the aspect ratio.


double aspectRatio = (double) img.getWidth(null)/(double) img.getHeight(null);
tempPNG = resizeImage(img, 100, (int) (100/aspectRatio));

Note that in this case, you would have to make sure that there are only images in the directory else it will throw exception.

Further Reading: Here is another program to upload files on server using Apache Commons Net FTP API.

Reference: Graphics2D API Doc

Comments

  1. Shobaraj says:

    hi im getting java.lang.UnsupportedOperationException: Not supported yet. on resizeImage. please get me a solution

  2. jj Lazzard says:

    please where can i download or find your code about it?
    i need for JPG image resizing, please help me.

    1. Oliver says:

      if you do not see the code above, try a different browser. For me, the code was invisible only when using IE.

  3. Amar says:

    Hi,

    Thank you. It is working for JPEG. But for PNG image, resized image quality is very poor. Please help

  4. rajesh says:

    Can Please Provide me the Complete Code for PDF To tiff using “pdfbox-0.7.3.jar”

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages