问题
I had searched about it but I did not get straight forward answer. I want a buffered image to be rotated but not cropped I knew the new dimensions are gonna be some thing like this
int w = originalImage.getWidth();
int h = originalImage.getHeight();
double toRad = Math.toRadians(degree);
int hPrime = (int) (w * Math.abs(Math.sin(toRad)) + h * Math.abs(Math.cos(toRad)));
int wPrime = (int) (h * Math.abs(Math.sin(toRad)) + w * Math.abs(Math.cos(toRad)));
Provide me a method for that.
BTW is there any way to rotate a JLabel
with an ImageIcon
?
Intention: adding to panels and layered pane and also saving it to file (saving the layered pane).
Or can we rotate the layered pane?
回答1:
How to rotate a buffered image without cropping it?
You had already half of the work by calculating the size of the rotated BufferedImage
.
The other half is actually creating the rotated BufferedImage
.
You can do that by using Graphics2D
and applying some coordinate transformations before drawing the original image onto the new one. Furthermore, it makes sense to paint the "excess" area with some background color.
public BufferedImage rotateImage(BufferedImage originalImage, double degree) {
int w = originalImage.getWidth();
int h = originalImage.getHeight();
double toRad = Math.toRadians(degree);
int hPrime = (int) (w * Math.abs(Math.sin(toRad)) + h * Math.abs(Math.cos(toRad)));
int wPrime = (int) (h * Math.abs(Math.sin(toRad)) + w * Math.abs(Math.cos(toRad)));
BufferedImage rotatedImage = new BufferedImage(wPrime, hPrime, BufferedImage.TYPE_INT_RGB);
Graphics2D g = rotatedImage.createGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, wPrime, hPrime); // fill entire area
g.translate(wPrime/2, hPrime/2);
g.rotate(toRad);
g.translate(-w/2, -h/2);
g.drawImage(originalImage, 0, 0, null);
g.dispose(); // release used resources before g is garbage-collected
return rotatedImage;
}
Here is a test example from the above code:
Original image
Rotated image (by 30 degree)
回答2:
BTW is there any way to rotate a JLabel with an ImageIcon?
The easier way is to rotate the Icon, not the label.
Check out Rotated Icon for a class that does the rotation and recalculates the size of the Icon as it is rotated.
Intention: adding to panels and layered pane and also saving it to file (saving the layered pane).
Don't know exactly what that means, but if you just want to save an "image" of the layered pane then check out Screen Image.
来源:https://stackoverflow.com/questions/44086310/how-to-rotate-a-buffered-image-without-cropping-it-is-there-any-way-to-rotate-a