Image Effects Creating Custom Image Cropping Interfaces in Android How to Create Simple Yet Effective PHP Overlay Understanding Real-Time Image Recognition How to add a shadow effect to an image with CSS How to crop an image in Flutter with Cloudinary How To Rotate an Image with Java Image Processing with Python Rotating an image with CSS Enhancing User Experience with a Responsive Image Slider Building a Python Image Recognition System Building an Interactive JavaScript Image Manipulation Tool Image Align Centering with HTML and CSS Efficient Image Cropping Techniques with Angular and Cloudinary Ultimate Guide to Photo Gallery on Android A Comprehensive Guide to Adding Text to Images on Android Mastering Background Changes in React Applications Comprehensive Guide on Changing Background on Android Devices Mastering Image Rotation in Java A Guide to Adding Text to Images with Python A Guide to Converting Images to Grayscale with Python Introduction Creating an Image Overlay with JavaScript Rotating an Image in Python Creating a Dynamic Photo Gallery with jQuery Creating An Interactive Photo Gallery Using JavaScript Mastering Overlay in Android Mastering Angular Overlay: A Comprehensive Guide Comprehensive Guide to Overlay in Flutter Mastering Overlay React for Responsive Design Solutions Create a Blurred Image with PHP: A Comprehensive Guide Guide to Using Blur Image in Flutter Mastering Blur Image in React Native Mastering Image Blurring in Python Mastering the Art of Image Blurring Mastering the Art of Image Blurring in Java The Ultimate Guide to Blurring Images on Android Understanding and Implementing Blur Image in JQuery An Extensive Walkthrough of Blurring Images with JavaScript How to Use HTML, CSS, and JavaScript to Make an Image Slider HTML Image Tag How to Crop GIFs? How to Align Images with CSS Ken Burns Effect – Complete Guide and How to Apply It Cartoonify – Complete Guide on Cartoonify Image Effect Mastering Web Aesthetics: A Comprehensive Guide to Gradient Fades Sepia Effect: The Ultimate Guide to the Sepia Photo Effect What is Vignette? Guide to Vignette Image Editing Pixelate – The Ultimate Guide to the Pixelation Effect How to Outline an Image: Enhancing Visual Appeal and Depth Make Your Photos Pop with Image Effects Upscale Image – Developers guide to AI-driven image upscaling Image Manipulation: History, Concepts and a Complete Guide A Full Guide to Object-aware Cropping Simplify Your Life with Automatic Image Tagging How To Resize Images In WordPress How To Create a Progress Bar For Asset Uploads Animated GIFs – What They Are And How To Create Them How To Automatically Improve Image Resolution AI Drop Shadow Get Image Dimensions From URLs Automatically Add Sepia Effect To Images Automatically Make an Image a Cartoon Automatically Add Blur Faces Effect To Images Automatically Add Background Removal Effect to an Image How to Resize an Image with React How to Easily Resize an Image with React Native

How To Rotate an Image with Java

java_rotate_image

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:

java_rotate_image

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 of Image 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 files
  • javax.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:

  1. The rotation angle in radians.
  2. The x-coordinate of the rotation center.
  3. 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.

java_rotate_image

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:

  1. Download and install Maven. See https://maven.apache.org/download.cgi for reference.
  2. Create a Maven project. See an example here.
  3. 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!

Last updated: Jun 18, 2024