Home  >  Article  >  Java  >  Java program to rotate image

Java program to rotate image

PHPz
PHPzforward
2023-09-01 16:25:031195browse

An image file can be rotated clockwise or counterclockwise. To rotate an image, you need to download a random image file and save it in any folder on your system. Also, a .pdf file is required and after opening the downloaded image file, some angle can be rotated in that particular .pdf file. For a 90 degree rotation, the anchor points of the new image can help us perform the rotation using the translation transform in Java. The anchor point is the center of any particular image.

Algorithm to Rotate an Image by Using Java

The "AffineTransformOp" class is the simplest way to rotate an image file by using Java. A user can load the image data as Buffered Image and apply the rotate operation using anchor point to produce the new BufferedImage for the next step. It is always recommended that to use JPEG files for these operations with JDeli(Filetype with wide range).

By using a Java program to rotate an image, programmers can use some built-in methods such as the BufferedImage class and Color c.

To use this process, we need to load an image into Java as a BufferedImage, then use the same function to rotate the image and save the data to a new file.

Now, let us discuss the algorithm to understand the above operations in a broader way -

  • Step 1 − The image is read and written, and imported into a file class representing the directory path.

  • Step 2 − Use IOException: handle errors.

  • Step 3 − For holding the particular image use the object called BufferedImage, a static method to save the data in RAM.

  • Step 4 - Use ImageIO for read and write operations.

  • Step 5 − Use Graphics2D class, to render 2D shapes.

Syntax

Code declaration: public static Image rotate(Image image, double angle)

According to this grammar, the steps to understand are as follows:

  • Parameters −

    • Image − Perform rotation operation

    • Angle− Arc rotation

  • Return − Rotated image file

The following process can use a Java program to rotate image files -

  • Step 1 − Load The Image File As BufferedImage In Java Environment To load an image file in Java −

BufferedImage image = ImageIO.read(new File("C:\path\to\image name.jpg"));
  • Step 2 − Rotate the image by 90 degree

  • To rotate an image file by 90 degree follow the below code −

final double rads = Math.toRadians(90);
final Rotate rotate = new Rotate(90);
BufferedImage rotatedImage = rotate.apply(image);
  • Step 3 Save the image file

Use Java ImageIO 
ImageIO.write(rotatedImage,"JPG",newFile("C:\path\to\rotatedImagename.jpg"));

Example

import java.awt.*;
import java.awt.image.BufferedImage;
public class Main {
   public static Image rotate(Image image, double angle) {
      BufferedImage bufImg = toBufferedImage(image);
      double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
      int w = bufImg.getWidth(), h = bufImg.getHeight();
      int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
      BufferedImage result = new BufferedImage(neww, newh, Transparency.TRANSLUCENT);
      Graphics2D g = result.createGraphics();
      g.translate((neww - w) / 2, (newh - h) / 2);
      g.rotate(angle, w / 2, h / 2);
      g.drawRenderedImage(bufImg, null);
      g.dispose();
      return result;
   } 
   public static BufferedImage toBufferedImage(Image image) {
      if (image instanceof BufferedImage) {
         return (BufferedImage) image;
      }
      BufferedImage buff = new BufferedImage(image.getWidth(null), image.getHeight(null),
      BufferedImage.TYPE_INT_ARGB);
      Graphics2D g = buff.createGraphics();
      g.drawImage(image, 0, 0, null);
      g.dispose();
      return buff;
   }
}

Rotation of an Image Using BufferedImage Function

By using a try-catch blocking method, we can handle the exceptions as they may disturb the flow of the code.

  • Document Class - The document class is mainly used to display PDF documents. In this particular Java program, we need to create a document class using the ie.documentobj function. This function is used to open and close PDF files.

  • PDF Writer Class − The function supports the PDF, XML,RTF file generations to code the image file rotation. The directory function we use here is fileOutputStream() to handle a file for a java code.

  • Output function − output.pdf is a function class that represents the output after performing operations using Java code. This function helps get the output of the provided input.

  • Functions −

    • image class.imgage.scaleToFit() - The function helps us to set up a size in the input file preset.

    • imageobj.setRotationDegrees() - the coder can use this to rotate the image in certain angle. It can be used as a parameter in the method we used.

    • documentobj.open() - This function helps the user to open a file during operation.

    • documentobj.close() - Use this function to close a .pdf file.

Example

package JavaApplication29;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;

public class JavaApplication29 {
   public static void main(String[] args) {
      try {
         Document documentobj = new Document(PageSize.A4, 20, 20, 20, 20);
         PdfWriter.getInstance(documentobj, new FileOutputStream("output.pdf"));
         documentobj.open();
         Image imageobj = Image.getInstance("C:\Users\lenovo\Desktop\RDD\Logo Org.jpg");
         imageobj.scaleToFit(200f, 200f);
         imageobj.setRotationDegrees(90);
         documentobj.add(imageobj);
         documentobj.close();
         System.out.println("Task completed");
      } catch (Exception e) {
         System.out.println("Exception occurred");
      }
   }
}

Output

Console display dimensions and execution popups by coding using possible methods in the program. A new image is saved after rotation.

Java program to rotate image

Conclusion

In this article, the process discussed above helps to rotate image files. For a 90 degree rotation, the program needs to set up a new image and all parameters need to be changed. Since the anchor point is still at the center of the image, the operation is the same for clockwise and counterclockwise rotation.

The above is the detailed content of Java program to rotate image. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete