Advertisement
DulcetAirman

rotateBufferedImage

Apr 12th, 2022 (edited)
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. package ch.claude_martin.foo;
  2.  
  3. import java.awt.Graphics2D;
  4. import java.awt.image.BufferedImage;
  5. import java.io.File;
  6. import java.io.IOException;
  7.  
  8. import javax.imageio.ImageIO;
  9.  
  10. public class SomeClass {
  11.     public static void main(String[] args) throws IOException {
  12.         var input = "C:/picture.jpg";
  13.         var output = "C:/rotated_picture.jpg";
  14.         var img = ImageIO.read(new File(input));
  15.         var rotated = rotateBufferedImage(img, -90);
  16.         ImageIO.write(rotated, "jpg", new File(output));
  17.     }
  18.  
  19.     /**
  20.      * Rotates an image. Note that an angle of -90 is equal to 270.
  21.      *
  22.      * @param img   The image to be rotated
  23.      * @param angle The angle in degrees (must be a multiple of 90°).
  24.      * @return The rotated image, or the original image, if the effective angle is
  25.      *         0°.
  26.      */
  27.     public static BufferedImage rotateBufferedImage(BufferedImage img, int angle) {
  28.         if (angle < 0) {
  29.             angle = 360 + (angle % 360);
  30.         }
  31.         if ((angle %= 360) == 0) {
  32.             return img;
  33.         }
  34.         final boolean r180 = angle == 180;
  35.         if (angle != 90 && !r180 && angle != 270)
  36.             throw new IllegalArgumentException("Invalid angle.");
  37.         final int w = r180 ? img.getWidth() : img.getHeight();
  38.         final int h = r180 ? img.getHeight() : img.getWidth();
  39.         final int type = img.getType() == BufferedImage.TYPE_CUSTOM ? BufferedImage.TYPE_INT_ARGB : img.getType();
  40.         final BufferedImage rotated = new BufferedImage(w, h, type);
  41.         final Graphics2D graphic = rotated.createGraphics();
  42.         graphic.rotate(Math.toRadians(angle), w / 2d, h / 2d);
  43.         final int offset = r180 ? 0 : (w - h) / 2;
  44.         graphic.drawImage(img, null, offset, -offset);
  45.         graphic.dispose();
  46.         return rotated;
  47.     }
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement