Java is a general-purpose programming language that provides several classes and libraries for working with images. Some of these include the inbuilt java.awt.Image
class and the javax.imageio
package. These classes and packages provide many utility methods related to image processing and manipulation.
Image processing in Java involves many operations, such as resizing and scaling, color adjustments, adding overlays, file conversion, etc. In this article, we’ll learn how to rotate an image in Java using both built-in classes and an external library such as Cloudinary.
In this article:
Rotating an image with java.awt.Image
class
Before we begin, this tutorial assumes you have at least basic experience with Java. Also, make sure you have the Java Development Kit (JDK) installed on your computer. You can download the latest version from the official Oracle website here.
Step 1: Import required modules
Naturally, we’ll need to import any of the required modules to make our app function as needed.
import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO;
Here’s what each imported module does:
java.awt.Graphics2D
: Provides methods for rendering 2D graphics, such as images and shapes.java.awt.geom.AffineTransform
: Defines a geometric transformation such as, rotation, translation, scaling for rendering graphics.java.awt.image.BufferedImage
:BufferedImage
is a subclass ofImage
that represents an image with an accessible buffer of image data. It provides methods for setting and getting pixel values and supports different image types.java.io.File
: This is used to specify the file path for reading and writing image filesjavax.imageio.ImageIO
: Provides methods for reading and writing images.
Step 2: Load the input image
First, we need to load the image file into a BufferedImage
object.
File inputFile = new File("dog_sample.jpg"); BufferedImage inputImage = ImageIO.read(inputFile);
Step 3: Define the rotation angle
Next, we need to define the angle by which we want to rotate the image. The angle is specified in radians. For example, to rotate the input image by 90 degrees clockwise, we can use the following code:
double rotationAngle = Math.toRadians(90);
Step 4: Create a transformation object
To rotate the image, we need to create an AffineTransform
object and apply the rotation transformation to it.
AffineTransform transform = new AffineTransform(); transform.rotate(rotationAngle, newWidth / 2, newHeight / 2); // Translate the image to keep it centered transform.translate((newWidth - width) / 2, (newHeight - height) / 2);
The rotate
method takes the following arguments:
- The rotation angle in radians.
- The x-coordinate of the rotation center.
- The y-coordinate of the rotation center.
In this case, we’re using the center of the image as the rotation center.
Step 5: Create an output image
Now, we need to create a new BufferedImage
object to hold the rotated image. The dimensions of the output image may be different from the input image due to the rotation. Here’s the code to calculate the new dimensions:
int width = inputImage.getWidth(); int height = inputImage.getHeight(); int newWidth = (int) Math.abs(width * Math.cos(rotationAngle)) + (int) Math.abs(height * Math.sin(rotationAngle)); int newHeight = (int) Math.abs(height * Math.cos(rotationAngle)) + (int) Math.abs(width * Math.sin(rotationAngle)); BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType());
Step 6: Rotate the image
Finally, we can rotate the image by rendering the input image onto the output image using the Graphics2D
class and the AffineTransform
object:
Graphics2D g2d = outputImage.createGraphics(); g2d.setTransform(transform); g2d.drawImage(inputImage, 0, 0, null); g2d.dispose();
Step 7: Save the rotated image
To save the output image to a file, we can use the ImageIO.write
method as follows:
File outputFile = new File("output.jpg"); ImageIO.write(outputImage, "jpg", outputFile); System.out.println("Image rotated successfully!");
Here’s the complete code:
import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class Rotate { public static void main(String[] args) { try { File inputFile = new File("dog_sample.jpg"); // Replace `dog_sample.jpg` with the actual name of your image file BufferedImage inputImage = ImageIO.read(inputFile); double rotationAngle = Math.toRadians(90); int width = inputImage.getWidth(); int height = inputImage.getHeight(); int newWidth = (int) Math.abs(width * Math.cos(rotationAngle)) + (int) Math.abs(height * Math.sin(rotationAngle)); int newHeight = (int) Math.abs(height * Math.cos(rotationAngle)) + (int) Math.abs(width * Math.sin(rotationAngle)); BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType()); AffineTransform transform = new AffineTransform(); transform.rotate(rotationAngle, newWidth / 2, newHeight / 2); transform.translate((newWidth - width) / 2, (newHeight - height) / 2); Graphics2D g2d = outputImage.createGraphics(); g2d.setTransform(transform); g2d.drawImage(inputImage, 0, 0, null); g2d.dispose(); File outputFile = new File("output.jpg"); ImageIO.write(outputImage, "jpg", outputFile); System.out.println("Image rotated successfully!"); } catch (Exception e) { e.printStackTrace(); } } }
But…
While it’s possible to use vanilla Java code for basic image manipulations, we often need to perform advanced image processing operations that can be time-consuming and error-prone. Additionally, handling large volumes of images with vanilla Java can be tedious and inefficient due to the significant computational resources and memory required.
Enter Cloudinary.
Cloudinary is a cloud-based media management platform that provides a comprehensive set of image transformation features, including resizing, cropping, rotation, overlay, effects, and more. To integrate its features into various applications, Cloudinary offers easy-to-use APIs and SDKs for various programming languages, including Java.
Rotate an image with Cloudinary
In this section, you’ll learn how to use Cloudinary to rotate an image in Java. To do this, we can use the Cloudinary Java SDKwhich contains several methods and functions for image and video transformations.
Using Cloudinary to upload and transform images requires having an account. If you don’t have a Cloudinary account, you can sign up for a free one. Once you create an account, copy your API credentials (Cloud Name, API Key, and API Secret) from your dashboard, as you’ll need them in your configuring your app.
The recommended way to use Cloudinary Java SDK is to use it with Maven. To use Cloudinary in a Maven project, you’d do the following:
- Download and install Maven. See https://maven.apache.org/download.cgi for reference.
- Create a Maven project. See an example here.
- Add the Cloudinary dependency to the list of dependencies in the pom.xml:
<dependencies> ... <dependency> <groupId>com.cloudinary</groupId> <artifactId>cloudinary-http44</artifactId> <version>[Cloudinary Java SDK version, e.g. 1.36.0]</version> </dependency> </dependencies>
Here’s the complete code to rotate an image using the Cloudinary Java SDK:
import com.cloudinary.Cloudinary; import com.cloudinary.Transformation; import com.cloudinary.utils.ObjectUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Map; public class CloudinaryImageRotator { public static void main(String[] args) { Cloudinary cloudinary = new Cloudinary(ObjectUtils.asMap( "cloud_name", "YOUR_CLOUD_NAME", "api_key", "YOUR_API_KEY", "api_secret", "YOUR_API_SECRET" )); try { // Upload the image File file = new File("dog_sample.jpg"); // Replace `dog_sample.jpg` with the actual name of your image file Map uploadResult = cloudinary.uploader().upload(file, ObjectUtils.emptyMap()); // Rotate the image Map rotateParams = ObjectUtils.asMap( "angle", 90, "crop", "scale" ); String rotatedImageUrl = cloudinary.url() .transformation(new Transformation().angle(90).crop("scale")) .generate(uploadResult.get("public_id").toString()); System.out.println("Image rotation successful:", rotatedImagegUrl); } catch (IOException e) { e.printStackTrace(); } } }
Final Thoughts
Rotating an image in Java can be daunting, especially for beginners who are new to the language. However, solutions like Cloudinary enable developers to achieve such tasks in an easy and efficient manner. If you haven’t already, sign up for a free Cloudinary account today to enjoy the limitless possibilities in cloud-based media asset management.
Transform and optimize your images and videos effortlessly with Cloudinary’s cloud-based solutions. Sign up for free today!