Skip to content

Commit

Permalink
Fix RotationImageEffect by properly calculating required image bounda…
Browse files Browse the repository at this point in the history
…ries without cropping

(side note: x2 is not the valid formula here)
  • Loading branch information
steffen-wilke committed Oct 5, 2024
1 parent ca2e6ca commit 141f0d7
Showing 1 changed file with 27 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,45 @@ public class RotationImageEffect extends ImageEffect {
* The angle by which this effect rotates the base image.
*/
public RotationImageEffect(final int ttl, final float angle) {
super(ttl, "RotationImageEffect");
super(ttl, "RotationImageEffect_" + angle);
this.angle = angle;
}

/**
* Applies a rotation transformation to the provided {@link BufferedImage}.
*
* This method rotates the given image by a specified angle, calculates the
* new dimensions needed to accommodate the rotated image without cropping,
* and creates a new compatible {@link BufferedImage} with those dimensions.
*
* @param image the {@link BufferedImage} to be rotated.
* If {@code null}, the method returns {@code null}.
*
* @return a new {@link BufferedImage} representing the rotated image,
* or {@code null} if the input image was {@code null}.
*
*/
@Override
public BufferedImage apply(final BufferedImage image) {
if (image == null) {
return null;
}

final int size = Math.max(image.getWidth(), image.getHeight()) * 2;
final BufferedImage img = Imaging.getCompatibleImage(size, size);
final Graphics2D g = img.createGraphics();
// Calculate the new dimensions after rotation
double radians = Math.toRadians(angle);
int width = image.getWidth();
int height = image.getHeight();

// Calculate the new width and height
int newWidth = (int) Math.abs(width * Math.cos(radians)) + (int) Math.abs(height * Math.sin(radians));
int newHeight = (int) Math.abs(height * Math.cos(radians)) + (int) Math.abs(width * Math.sin(radians));

final BufferedImage rotatedImage = Imaging.getCompatibleImage(newWidth, newHeight);
final Graphics2D g = rotatedImage.createGraphics();
ImageRenderer.renderRotated(g, image, new Point2D.Double(0, 0), this.getAngle());
g.dispose();

return img;
return rotatedImage;
}

public double getAngle() {
Expand Down

0 comments on commit 141f0d7

Please sign in to comment.