// Thanks to ChatGPT static BufferedImage rotateImage(BufferedImage image, double angle) { int width = image.getWidth(); int height = image.getHeight(); // Calculate new image size to fit rotated image double radians = Math.toRadians(angle); double sin = Math.abs(Math.sin(radians)); double cos = Math.abs(Math.cos(radians)); int newWidth = (int) Math.floor(width * cos + height * sin); int newHeight = (int) Math.floor(height * cos + width * sin); // Create new image with transparent background BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = rotated.createGraphics(); AffineTransform at = new AffineTransform(); // Translate to center of image and rotate at.translate((newWidth - width) / 2, (newHeight - height) / 2); at.rotate(radians, width / 2, height / 2); // Draw original image onto new image with transformation g2d.setTransform(at); g2d.drawImage(image, 0, 0, null); g2d.dispose(); return rotated; }