Rotate bufferedimage in java

Java Program to Rotate an Image

A image file can rotated clockwise or anticlockwise direction. To rotate an image it is needed to download a random image file and save it in any folder on your system. Further, a .pdf file is required to create and rotate some degrees after opening the downloaded image in that particular .pdf file. For 90 degree rotations, anchor point of a new image help us to perform the rotation operation using the translate transformation in Java. The anchor point is the center for 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 operation with JDeli(Filetype with wide range).

To rotate an image by using Java program a coder can use some in-built methods, like BufferedImage class and Color c.

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

Now, let us discuss the algorithm to understand the above operation in a broad manner −

  • Step 1 − Image read and write and import to the file class which presents 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 to run read and write operation.
  • Step 5 − Use Graphics2D class, to render 2D shapes.

Syntax

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

According to this syntax, there are some steps to understand −

  • Parameters −
    • Image − To perform the rotate operation
    • Angle − Radian rotation

    Below processes can be used to rotate an image File by using Java Program −

    • 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"));

    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);
    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 − Document class is mainly used to present the pdf document. Here in this particular java program we need to create a document class by using ie.documentobj function. This function is used to open and close the pdf file.
    • 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 which denotes the output after performing the operation using the Java code. This function helps to get the output on the input provided.
    • 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() — The function help the user to open a file at the time of operation.
      • documentobj.close() — To close a .pdf file this function is used.

      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

      By using the possible method is encoded in the program, the console shows the dimensions and execution pop-up. A new image is saved after rotation.

      Conclusion

      In this article, the above discussed processes help to rotate an image file. For 90 degree rotation, a program needs to set a new image, all parameters are needed to be changed. Since the anchor point remains in the center of the image and the operation is same both for clockwise and anti-clockwise rotation.

      Источник

      Rotate an Image in Java

      Rotate an Image in Java

      1. Rotate an Image in Java Using BufferedImage and Graphics2D.rotate()
      2. Rotate an Image in Java Using Affine Transform

      This article will introduce how we can rotate an image in Java using two native ways.

      Rotate an Image in Java Using BufferedImage and Graphics2D.rotate()

      The first method to rotate an image includes the use of the BufferedImage and the Graphics2d class that comes with the AWT package. Below we create a function rotateImage() that receives a BufferedImage object as a parameter and returns a rotated BufferedImage object.

      In rotateImage() , we get the width, height and the type of the image using getWidth() , getHeight() and getType() methods. Now we call the BufferedImage() constructor and pass the three variables as arguments and it returns a BufferedImage object newImageFromBuffer .

      We create new rotated image using createGraphics() method that returns a Graphics2D object graphics2D . Using this object, we call the rotate() function that takes three arguments; the first is the angle to rotate the image as we want to rotate it 90 degrees we pass Math.radians(90) , the second and third arguments are the x and y coordinates.

      Finally, we call graphics2D.drawImage() to draw the rotated image, which takes four arguments, the BufferedImage object, the filter to apply, and the x and y coordinates. Then we return the newImageFromBuffer object.

      In the main function, we read the file using File and then convert it into a BufferedImage object using ImageIO.read() . Now we call the rotateImage() function and pass the returned BufferedImage object and store the rotated BufferedImage object. Now that we have the rotated image, we need to create a new file to store it using File and ImageIO.write() that takes the BufferedImage object, its extension the location of the empty file.

      import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException;  public class RotateImage    public static BufferedImage rotateImage(BufferedImage imageToRotate)   int widthOfImage = imageToRotate.getWidth();  int heightOfImage = imageToRotate.getHeight();  int typeOfImage = imageToRotate.getType();   BufferedImage newImageFromBuffer = new BufferedImage(widthOfImage, heightOfImage, typeOfImage);   Graphics2D graphics2D = newImageFromBuffer.createGraphics();   graphics2D.rotate(Math.toRadians(90), widthOfImage / 2, heightOfImage / 2);  graphics2D.drawImage(imageToRotate, null, 0, 0);   return newImageFromBuffer;  >   public static void main(String[] args)    try    BufferedImage originalImage = ImageIO.read(new File("mountains.jpeg"));   BufferedImage subImage = rotateImage(originalImage);   File rotatedImageFile = new File("C:\\Users\\User1\\Documents\\mountainsRotated.jpeg");   ImageIO.write(subImage, "jpg", rotatedImageFile);   System.out.println("New Rotated Image File Path: "+rotatedImageFile.getPath());   > catch (IOException e)   e.printStackTrace();  >  >  > 
      New Rotated Image File Path: C:\Users\User1\Documents\mountainsRotated.jpeg 

      rotate image in java - original image

      rotate image in java - rotated image

      Rotate an Image in Java Using Affine Transform

      This example uses the AffineTransform class that maps an image from its original 2D coordinates to other 2D coordinates linearly without losing the original quality. In the following program, we three methods, one to read and call other functions, the second is to rotate the image clockwise, and the last function rotates the image counterclockwise.

      In the rotateImage() function, we read the image using new File() and convert it to a BufferedImage object using ImageIO.read() . Then we create another BufferedImage object that preserves the properties of the original image and call it output . Next we call the rotateImageClockWise() method and pass the original BufferedImage in it that returns an object of AffineTransorm class.

      rotateImageClockWise() receive the image and get the height and width. We create a AffineTransform object affineTransform and call rotate() method using it. In rotate() , we pass three arguments; the first is the rotate angle measured in radians, here we pass Math.PI / 2 , the last two arguments are the x and y coordinates which are half of the width and height of the image.

      Now, as the image is rotated, we translate the image in the new coordinates using the translate() function that takes two arguments: the distance to rotate in the x-direction and the distance to rotate in the y-direction. We calculate the x and y arguments using (imageWidth — imageHeight) / 2 .

      To rotate the image counter clockwise, we can call the method rotateImageCounterClockwise() in rotate() instead of rotateImageClockWise() .

      import javax.imageio.ImageIO; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File;  public class RotateImage    private static final String INPUT_FILE_NAME = "mountains.jpeg";  private static final String OUTPUT_FILE_NAME = "mountainsRotated.jpeg";   private AffineTransform rotateImageClockWise(BufferedImage image)    int imageWidth = image.getWidth();  int imageHeight = image.getHeight();   AffineTransform affineTransform = new AffineTransform();  affineTransform.rotate(Math.PI / 2, imageWidth / 2, imageHeight / 2);   double offset = (imageWidth - imageHeight) / 2;  affineTransform.translate(offset, offset);  return affineTransform;  >   private AffineTransform rotateImageCounterClockwise(BufferedImage image)    int imageWidth = image.getWidth();  int imageHeight = image.getHeight();   AffineTransform affineTransform = new AffineTransform();  affineTransform.rotate(-Math.PI / 2, imageWidth / 2, imageHeight / 2);   double offset = (imageWidth - imageHeight) / 2;  affineTransform.translate(-offset, -offset);   return affineTransform;  >   private void rotateImage() throws Exception   BufferedImage bufferedImage = ImageIO.read(new File(INPUT_FILE_NAME));   BufferedImage output = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(), bufferedImage.getType());   AffineTransform affineTransform = rotateImageClockWise(bufferedImage);  AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR);  affineTransformOp.filter(bufferedImage, output);   ImageIO.write(output, "jpg", new File(OUTPUT_FILE_NAME));   >   public static void main(String[] args)    try    RotateImage rotateImage = new RotateImage();  rotateImage.rotateImage();   > catch (Exception e)   e.printStackTrace();  >  > > 

      rotate image in java - original image

      rotate image in java - clockwise rotated image

      Image Rotated Counter Clockwise:

      rotate image in java - counter-clockwise rotated image

      Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

      Related Article — Java Image

      Источник

      Читайте также:  Java unit test rest
Оцените статью