Java Scale Image File using Imgscalr
Tags: Imgscalr BufferedImage ImageIO Image File Scale Image Scalr
In this Java tutorial we learn how to scale an image file using the Scalr class of Imgscalr Java 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 scale an image file in Java
The Imgscalr library provides the method Scalr.resize() to allow resizing a given image. By using this method we can scale an image file to a smaller or bigger version. The Java example code below to show you how to scale an image using the Scalr.resize() method.
ScaleImageExample.java
import org.imgscalr.Scalr;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ScaleImageExample {
public static void main(String... args) {
String originalFilePath = "D:\\TestData\\Albert_Einstein.jpg";
String scaleFilePath1 = "D:\\TestData\\Albert_Einstein_big.jpg";
String scaleFilePath2 = "D:\\TestData\\Albert_Einstein_small.jpg";
scaleImage(originalFilePath, scaleFilePath1, 5.5);
scaleImage(originalFilePath, scaleFilePath2, 0.3);
}
public static void scaleImage(String originalFilePath, String scaleFilePath, double scaleRatio) {
try {
File sourceFile = new File(originalFilePath);
BufferedImage originalImage = ImageIO.read(sourceFile);
int width = (int)Math.ceil(originalImage.getWidth() * scaleRatio);
int height = (int)Math.ceil(originalImage.getHeight() * scaleRatio);
BufferedImage thumbnailImage = Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY, width, height);
File thumbnailFile = new File(scaleFilePath);
ImageIO.write(thumbnailImage, "jpg", thumbnailFile);
originalImage.flush();
thumbnailImage.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Happy Coding 😊