Java BufferedImage Rotate rotateImage(BufferedImage image, double angle)

Here you can find the source of rotateImage(BufferedImage image, double angle)

Description

Rotates an image.

License

Apache License

Parameter

Parameter Description
image the original image
angle the degree of rotation

Return

a rotated image

Declaration

public static BufferedImage rotateImage(BufferedImage image, double angle) 

Method Source Code

//package com.java2s;
/**/*from  ww w  . jav a2 s . co m*/
 * Copyright @ 2008 Quan Nguyen
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import java.awt.*;

import java.awt.image.*;

public class Main {
    /**
     * Rotates an image.
     * 
     * @param image the original image
     * @param angle the degree of rotation
     * @return a rotated image
     */
    public static BufferedImage rotateImage(BufferedImage image, double angle) {
        double theta = Math.toRadians(angle);
        double sin = Math.abs(Math.sin(theta));
        double cos = Math.abs(Math.cos(theta));
        int w = image.getWidth();
        int h = image.getHeight();
        int newW = (int) Math.floor(w * cos + h * sin);
        int newH = (int) Math.floor(h * cos + w * sin);

        BufferedImage tmp = new BufferedImage(newW, newH, image.getType());
        Graphics2D g2d = tmp.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.translate((newW - w) / 2, (newH - h) / 2);
        g2d.rotate(theta, w / 2, h / 2);
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        return tmp;
    }
}

Related

  1. rotateAndFlipSwappingRowsAndColumns(BufferedImage srcImage)
  2. rotateBufferedImage(BufferedImage bufferedImage, double angle)
  3. rotateByRightAngle(BufferedImage source, int degrees)
  4. rotateFortyFiveClockwise(BufferedImage img)
  5. rotateImage(BufferedImage image, double angle)
  6. rotateImage(BufferedImage image, double radians)
  7. rotateImage(BufferedImage image, float angle)
  8. rotateImage(BufferedImage image, int cwRotationNeeded)
  9. rotateImage(BufferedImage imageToRotate, float degrees)