Here you can find the source of rotate(final BufferedImage image, final int angle)
Parameter | Description |
---|---|
image | image to be rotated. |
angle | angle to rotate image to |
public static BufferedImage rotate(final BufferedImage image, final int angle)
//package com.java2s; //License from project: Apache License import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; public class Main { /**//from ww w . j av a 2s.c o m * Rotates given image to given angle. * @param image image to be rotated. * @param angle angle to rotate image to * @return rotated image. */ public static BufferedImage rotate(final BufferedImage image, final int angle) { if (image == null) { throw new IllegalArgumentException("\"image\" param cannot be null."); } final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); final Map<String, Integer> boundingBoxDimensions = calculateRotatedDimensions(imageWidth, imageHeight, angle); final int newWidth = boundingBoxDimensions.get("width"); final int newHeight = boundingBoxDimensions.get("height"); final BufferedImage newImage = new BufferedImage(newWidth, newHeight, image.getType()); final Graphics2D newImageGraphic = newImage.createGraphics(); final AffineTransform transform = new AffineTransform(); transform.setToTranslation((newWidth - imageWidth) / 2, (newHeight - imageHeight) / 2); transform.rotate(Math.toRadians(angle), imageWidth / 2, imageHeight / 2); newImageGraphic.drawImage(image, transform, null); newImageGraphic.dispose(); return newImage; } private static Map<String, Integer> calculateRotatedDimensions(final int imageWidth, final int imageHeight, final int angle) { final Map<String, Integer> dimensions = new HashMap<String, Integer>(); // coordinates of our given image final int[][] points = { { 0, 0 }, { imageWidth, 0 }, { 0, imageHeight }, { imageWidth, imageHeight } }; final Map<String, Integer> boundBox = new HashMap<String, Integer>() { { put("left", 0); put("right", 0); put("top", 0); put("bottom", 0); } }; final double theta = Math.toRadians(angle); for (final int[] point : points) { final int x = point[0]; final int y = point[1]; final int newX = (int) (x * Math.cos(theta) + y * Math.sin(theta)); final int newY = (int) (x * Math.sin(theta) + y * Math.cos(theta)); //assign the bounds boundBox.put("left", Math.min(boundBox.get("left"), newX)); boundBox.put("right", Math.max(boundBox.get("right"), newX)); boundBox.put("top", Math.min(boundBox.get("top"), newY)); boundBox.put("bottom", Math.max(boundBox.get("bottom"), newY)); } // now get the dimensions of the new box. dimensions.put("width", Math.abs(boundBox.get("right") - boundBox.get("left"))); dimensions.put("height", Math.abs(boundBox.get("bottom") - boundBox.get("top"))); return dimensions; } }