Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rotating an image 90 degrees in java [duplicate]

I have managed to rotate an image 180 degrees but wish to rotate it 90 degrees clockwise can someone edit my code so that it does this with explanation. Thanks.

 private void rotateClockwise()
    {
        if(currentImage != null){
            int width = currentImage.getWidth();
            int height = currentImage.getHeight();
            OFImage newImage = new OFImage(width, height);
            for(int y = 0; y < height; y++) {
                for(int x = 0; x < width; x++) {
                    newImage.setPixel( x, height-y-1, currentImage.getPixel(x, y));
                }
        }
            currentImage = newImage;
            imagePanel.setImage(currentImage);
            frame.pack();
    }
    }
like image 464
Ryan Gibson Avatar asked Apr 10 '13 13:04

Ryan Gibson


People also ask

How do you rotate an object 90 degrees in Java?

As discussed here, you can use AffineTransformOp to rotate an image by Math. PI / 2 ; this is equivalent to rotating the image clockwise 90°, as shown here.

How do you rotate an image 90 degrees clockwise?

Answer: To rotate the figure 90 degrees clockwise about a point, every point(x,y) will rotate to (y, -x). Let's understand the rotation of 90 degrees clockwise about a point visually.

How do I flip an image 90 degrees?

Rotate 90 degrees Under Drawing Tools (or Picture Tools if you're rotating a picture), on the Format tab, in the Arrange group, click Rotate, and then: To rotate the object 90 degrees to the right, click Rotate Right 90°.


1 Answers

Use this method.

/**
 * Rotates an image. Actually rotates a new copy of the image.
 * 
 * @param img The image to be rotated
 * @param angle The angle in degrees
 * @return The rotated image
 */
public static Image rotate(Image img, double angle)
{
    double sin = Math.abs(Math.sin(Math.toRadians(angle))),
           cos = Math.abs(Math.cos(Math.toRadians(angle)));

    int w = img.getWidth(null), h = img.getHeight(null);

    int neww = (int) Math.floor(w*cos + h*sin),
        newh = (int) Math.floor(h*cos + w*sin);

    BufferedImage bimg = toBufferedImage(getEmptyImage(neww, newh));
    Graphics2D g = bimg.createGraphics();

    g.translate((neww-w)/2, (newh-h)/2);
    g.rotate(Math.toRadians(angle), w/2, h/2);
    g.drawRenderedImage(toBufferedImage(img), null);
    g.dispose();

    return toImage(bimg);
}

taken from my ImageTool class.

Hope it helps.

like image 105
Sri Harsha Chilakapati Avatar answered Nov 11 '22 00:11

Sri Harsha Chilakapati