Introduction:
Image rotation is a fundamental operation in image processing, often used in applications like photo editing, computer vision, and graphics transformation. In Java, you can rotate an image using the Affine Transform class from the java.awt.geom package or by manually manipulating pixel positions.
In this guide, we Using Affine Transform method:
The Affine Transform class provides built-in methods to perform scaling, translation, rotation, and shearing of images efficiently.
Steps to Rotate an Image:
-
Load the image using ImageIO.read() .
-
Create an Affine Transform object and set the rotation angle.
-
Use Graphics2D to apply the transformation.
-
Save the rotated image using ImageIO.write() .
here is Example :
import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageRotator { public static void main(String[] args) { try { // Load the image File inputFile = new File("input.jpg"); // Replace with your image path BufferedImage originalImage = ImageIO.read(inputFile); // Define rotation angle (90 degrees = Math.PI/2) double angle = Math.toRadians(90); // Rotate 90 degrees // Calculate new image dimensions int width = originalImage.getWidth(); int height = originalImage.getHeight(); int newWidth = height; int newHeight = width; // Create a new blank rotated image BufferedImage rotatedImage = new BufferedImage(newWidth, newHeight, originalImage.getType()); // Apply AffineTransform for rotation Graphics2D graphics = rotatedImage.createGraphics(); AffineTransform transform = new AffineTransform(); transform.rotate(angle, width / 2.0, height / 2.0); transform.translate((newWidth - width) / 2.0, (newHeight - height) / 2.0); graphics.setTransform(transform); graphics.drawImage(originalImage, 0, 0, null); graphics.dispose(); // Save the rotated image File outputFile = new File("rotated.jpg"); ImageIO.write(rotatedImage, "jpg", outputFile); System.out.println("Image rotated successfully!"); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }
Use Cases of Image Rotation:
-
Photo Editing Software → Users can rotate images to fix orientation.
-
Computer Vision → Aligning images for object detection.
-
Game Development → Rotating sprites dynamically.
-
Barcode Scanning → Adjusting image orientation for accurate scanning.
Conclusion:
Rotating an image in Java can be accomplished using AffineTransform for a built-in, optimized approach or manual pixel manipulation for deeper learning. The method is faster and more efficient, making it the recommended choice for real-world applications.