Java Resize Images in Directory using Imgscalr

Tags: Imgscalr BufferedImage ImageIO Image File FileFilter Directory Resize Image Scalr

In this Java tutorial we learn how to resize all image files in a specific directory using the Java Imgscalr library.

How to add Imgscalr library to the Java project

To use the Imgscalr library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.imgscalr:imgscalr-lib:4.2'

To use the Imgscalr library in the Maven build project, add the following dependency into the pom.xml file.

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

To have more information about the Imgscalr library you can visit the project repository at github.com/rkalla/imgscalr

How to resize all images in a directory

The Imgscalr library provides the Scalr.resize() method to resize image files. In the following Java code we show you how to use the Scalr.resize() method to resize all image files with .jpg file extension in a given directory.

ResizeImagesInDirectory.java

import org.imgscalr.Scalr;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Paths;

public class ResizeImagesInDirectory {
    public static void main(String... args) {
        String sourceDirectory = "D:\\TestData\\";
        String destinationDirectory = "D:\\TestData\\Resized";
        int targetSize = 100;

        resizeImage(sourceDirectory, destinationDirectory, targetSize);
    }

    public static void resizeImage(String sourceDirectory, String destinationDirectory, int targetSize) {
        try {
            File directory = new File(sourceDirectory);
            if(!directory.exists())
                return;

            FileFilter fileFilter = file -> file.isFile() && file.getName().endsWith(".jpg");
            File[] listOfFiles = directory.listFiles(fileFilter);
            for(File sourceFile : listOfFiles) {
                BufferedImage originalImage = ImageIO.read(sourceFile);

                BufferedImage resizedImage = Scalr.resize(originalImage, targetSize);

                File resizedFile = Paths.get(destinationDirectory, sourceFile.getName()).toFile();
                ImageIO.write(resizedImage, "jpg", resizedFile);
                originalImage.flush();
                resizedImage.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:

Java Resize Images in Directory using Imgscalr

Java Resize Images in Directory using Imgscalr

Happy Coding 😊