Java Image Rotate rotate(Image image, double angle)

Here you can find the source of rotate(Image image, double angle)

Description

Rotates an Image object.

License

Open Source License

Parameter

Parameter Description
image the image to rotate
angle rotation in radians

Return

rotated image

Declaration

public static Image rotate(Image image, double angle) 

Method Source Code


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

import java.awt.*;

import java.awt.image.BufferedImage;

public class Main {
    /**/*from  ww w .  java 2  s. co m*/
     * Rotates an Image object. Taken from http://stackoverflow.com/a/4156760/2159348.
     * @param image the image to rotate
     * @param angle rotation in radians
     * @return rotated image
     */
    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;
    }

    /**
     * Converts an image to a buffered image.
     * @param image the image to be converted
     * @return buffered image
     */
    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;
    }
}

Related

  1. imageRotate(Image img, int angle)
  2. rotate(File sourceImage, String targetImageName, double degree)
  3. rotate(Image img, double angle)
  4. rotate(Image img, double angle)
  5. rotate(Image img, float radian)
  6. Rotate(Image src, int angel)