Libraryless. Click here for Pure Java version (59L/1K).
1 | // Thanks to ChatGPT |
2 | |
3 | static BufferedImage rotateImage(BufferedImage image, double angle) { |
4 | int width = image.getWidth(); |
5 | int height = image.getHeight(); |
6 | |
7 | // Calculate new image size to fit rotated image |
8 | double radians = Math.toRadians(angle); |
9 | double sin = Math.abs(Math.sin(radians)); |
10 | double cos = Math.abs(Math.cos(radians)); |
11 | int newWidth = (int) Math.floor(width * cos + height * sin); |
12 | int newHeight = (int) Math.floor(height * cos + width * sin); |
13 | |
14 | // Create new image with transparent background |
15 | BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); |
16 | Graphics2D g2d = rotated.createGraphics(); |
17 | AffineTransform at = new AffineTransform(); |
18 | |
19 | // Translate to center of image and rotate |
20 | at.translate((newWidth - width) / 2, (newHeight - height) / 2); |
21 | at.rotate(radians, width / 2, height / 2); |
22 | |
23 | // Draw original image onto new image with transformation |
24 | g2d.setTransform(at); |
25 | g2d.drawImage(image, 0, 0, null); |
26 | g2d.dispose(); |
27 | |
28 | return rotated; |
29 | } |
download show line numbers debug dex old transpilations
Travelled to 2 computer(s): mqqgnosmbjvj, wnsclhtenguj
No comments. add comment
Snippet ID: | #1036553 |
Snippet name: | rotateImage - rotate image into a new image just big enough to fit, with transparent background |
Eternal ID of this version: | #1036553/1 |
Text MD5: | 34a33d7ecce17923743c2dda87fc79bb |
Transpilation MD5: | 7bdb6b36ea9d2a592a79815754f2a4ab |
Author: | stefan |
Category: | javax / imaging |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2023-02-13 18:55:03 |
Source code size: | 1047 bytes / 29 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 133 / 192 |
Referenced in: | [show references] |