Java Resize Image File using Imgscalr
Tags: Imgscalr BufferedImage ImageIO File Image File Resize Image Scalr
In this Java tutorial we learn how to resize an image file using the Scalr class of 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 an image in Java
The Imgscalr library provides the method Scalr.resize() to resize an image. In the following Java program we show you how to use the Scalr.resize() method to resize an image with a given target size and also maintain the original proportion of the image file.
ResizeImageExample.java
import org.imgscalr.Scalr;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ResizeImageExample {
public static void main(String... args) {
String originalFilePath = "D:\\TestData\\logo.jpg";
String targetFilePath = "D:\\TestData\\logo-60.jpg";
int targetSize = 600;
resizeImage(originalFilePath, targetFilePath, targetSize);
}
public static void resizeImage(String originalFilePath, String targetFilePath, int targetSize) {
try {
File sourceFile = new File(originalFilePath);
BufferedImage originalImage = ImageIO.read(sourceFile);
BufferedImage resizedImage = Scalr.resize(originalImage, targetSize);
File resizedFile = new File(targetFilePath);
ImageIO.write(resizedImage, "jpg", resizedFile);
originalImage.flush();
resizedImage.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Happy Coding 😊