Java Rotate Image File using Imgscalr
Tags: Imgscalr BufferedImage ImageIO File Image File Rotate Image Scalr
In this Java tutorial we learn how to rotate 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 rotate an image in Java
The Imgscalr library provides the Scalr.rotate() method to rotate a given image. We show you how to use the Scalr.rotate() method in the following Java example program.
RotateImageExample.java
import org.imgscalr.Scalr;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class RotateImageExample {
public static void main(String... args) {
String originalFilePath = "D:\\TestData\\logo.jpg";
String targetFilePathCw90 = "D:\\TestData\\logo-rotate-cw90.jpg";
String targetFilePathCw180 = "D:\\TestData\\logo-rotate-cw180.jpg";
String targetFilePathCw270 = "D:\\TestData\\logo-rotate-cw270.jpg";
String targetFilePathFlipHorz = "D:\\TestData\\logo-rotate-FlipHorz.jpg";
String targetFilePathFlipVert = "D:\\TestData\\logo-rotate-FlipVert.jpg";
rotateImage(originalFilePath, targetFilePathCw90, Scalr.Rotation.CW_90);
rotateImage(originalFilePath, targetFilePathCw180, Scalr.Rotation.CW_180);
rotateImage(originalFilePath, targetFilePathCw270, Scalr.Rotation.CW_270);
rotateImage(originalFilePath, targetFilePathFlipHorz, Scalr.Rotation.FLIP_HORZ);
rotateImage(originalFilePath, targetFilePathFlipVert, Scalr.Rotation.FLIP_VERT);
}
public static void rotateImage(String originalFilePath, String targetFilePath, Scalr.Rotation rotation) {
try {
File sourceFile = new File(originalFilePath);
BufferedImage originalImage = ImageIO.read(sourceFile);
BufferedImage resizedImage = Scalr.rotate(originalImage, rotation);
File resizedFile = new File(targetFilePath);
ImageIO.write(resizedImage, "jpg", resizedFile);
originalImage.flush();
resizedImage.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Happy Coding 😊