Java BufferedImage Rotate rotateImage(BufferedImage src, double degrees)

Here you can find the source of rotateImage(BufferedImage src, double degrees)

Description

Rotates a BufferedImage

License

Open Source License

Parameter

Parameter Description
src Source image
degrees Angle in degrees

Return

Rotated image

Declaration

public static BufferedImage rotateImage(BufferedImage src, double degrees) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.*;
import java.awt.image.BufferedImage;

public class Main {
    /**/*from   w  w  w .j a  v  a 2 s . c om*/
     * Rotates a BufferedImage
     *
     * @param src     Source image
     * @param degrees Angle in degrees
     * @return Rotated image
     */
    public static BufferedImage rotateImage(BufferedImage src, double degrees) {
        double radians = Math.toRadians(degrees);

        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();

        double sin = Math.abs(Math.sin(radians));
        double cos = Math.abs(Math.cos(radians));
        int newWidth = (int) Math.floor(srcWidth * cos + srcHeight * sin);
        int newHeight = (int) Math.floor(srcHeight * cos + srcWidth * sin);

        BufferedImage result = new BufferedImage(newWidth, newHeight, src.getType());
        Graphics2D g = result.createGraphics();
        g.translate((newWidth - srcWidth) / 2, (newHeight - srcHeight) / 2);
        g.rotate(radians, srcWidth / 2, srcHeight / 2);
        g.drawRenderedImage(src, null);

        return result;
    }
}

Related

  1. rotateImage(BufferedImage image, int cwRotationNeeded)
  2. rotateImage(BufferedImage imageToRotate, float degrees)
  3. rotateImage(BufferedImage img, double angle)
  4. rotateImage(BufferedImage img, double angle, int type)
  5. rotateImage(BufferedImage img, double degree)
  6. rotateImage(final BufferedImage image, final double theta)
  7. rotateImage(final BufferedImage savedImage, final int angle)
  8. rotateImage(final BufferedImage src, final double degrees)
  9. rotateImage180(BufferedImage image, final int bufferedImageType)