Get BufferedImage from ImageIcon
All transformations to images are usually done to the BufferedImage. You can get Image from ImageIcon and then convert it to BufferedImage:
Image image = icon.getImage();
BufferedImage bi = new BufferedImage(
image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
Rotate
Then you can rotate it -90 to 90 degrees using following code:
public BufferedImage rotate(BufferedImage bi, float angle) {
AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(angle), bi.getWidth() / 2.0, bi.getHeight() / 2.0);
at.preConcatenate(findTranslation(at, bi, angle));
BufferedImageOp op =
new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
return op.filter(bi, null);
}
private AffineTransform findTranslation(
AffineTransform at, BufferedImage bi, float angle) {
Point2D p2din = null, p2dout = null;
if (angle > 0 && angle <= 90) {
p2din = new Point2D.Double(0, 0);
} else if (angle < 0 && angle >= -90) {
p2din = new Point2D.Double(bi.getWidth(), 0);
}
p2dout = at.transform(p2din, null);
double ytrans = p2dout.getY();
if (angle > 0 && angle <= 90) {
p2din = new Point2D.Double(0, bi.getHeight());
} else if (angle < 0 && angle >= -90) {
p2din = new Point2D.Double(0, 0);
}
p2dout = at.transform(p2din, null);
double xtrans = p2dout.getX();
AffineTransform tat = new AffineTransform();
tat.translate(-xtrans, -ytrans);
return tat;
}
This works great rotating image from -90 up to 90 degrees, it does not support more than that. You can run through AffineTransform documentation for more explanation on working with the coordinates.
Set BufferedImage to ImageIcon
Finally you populate ImageIcon with transformed Image: icon.setImage((Image) bi);
.