0

my problem is very simple:

I've got an ImageIcon, and i want to obtain another one that is rotated exactly rotation*90° times. This is the method:

private ImageIcon setRotation(ImageIcon icon, int rotation);

I would prefer not having to use an external class. Thanks

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Tunarock
  • 127
  • 1
  • 1
  • 12
  • 1
    possible duplicate of [Rotate JLabel or ImageIcon on Java Swing](http://stackoverflow.com/questions/4287499/rotate-jlabel-or-imageicon-on-java-swing) – oers May 31 '12 at 10:03

1 Answers1

2

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);.

d1e
  • 6,372
  • 2
  • 28
  • 41