Java Create Thumbnail Image using Imgscalr
Tags: Imgscalr BufferedImage ImageIO File Image File Resize Image Thumbnail Scalr
In this Java tutorial we learn how to create thumbnail images by 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 create thumbnail image in Java
The Imgscalr library provides the Scalr.resize() method to resize a given image. By using this method we can create a thumbnail image as the below Java example code.
ThumbnailImageExample.java
import org.imgscalr.Scalr;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ThumbnailImageExample {
public static void main(String... args) {
String originalFilePath = "D:\\TestData\\logo.jpg";
String thumbnailFilePath = "D:\\TestData\\thumbnail.jpg";
int thumbnailSize = 100;
createThumbnailImage(originalFilePath, thumbnailFilePath, thumbnailSize);
}
public static void createThumbnailImage(String originalFilePath, String targetFilePath, int thumbnailSize) {
try {
File sourceFile = new File(originalFilePath);
BufferedImage originalImage = ImageIO.read(sourceFile);
BufferedImage thumbnailImage = Scalr.resize(originalImage, thumbnailSize);
File thumbnailFile = new File(targetFilePath);
ImageIO.write(thumbnailImage, "jpg", thumbnailFile);
originalImage.flush();
thumbnailImage.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Happy Coding 😊