Pernicious Rage
Pernicious Rage

Reputation: 35

How can I create a method in Java that rotates an image 90 degrees clockwise?

This is what I have so far:

public static Photograph rotated(Photograph photo) {
    Photograph rotated_copy = new Photograph(photo.getHeight(), photo.getWidth());
    Pixel starting_pixel = photo.getPixel(0,0);

    for(int col = 0; col < photo.getWidth(); col++){
        for(int row = 0; row < photo.getHeight(); row++){
            starting_pixel = photo.getPixel(col,row);
            rotated_copy.setPixel(row, col, starting_pixel);
        }
    }
    return rotated_copy;
}

However, this method rotates any Photograph taken in 90 degrees counter-clockwise. How can I fix this?

Upvotes: 1

Views: 3357

Answers (2)

SpacePrez
SpacePrez

Reputation: 1086

EDIT: Hm, unfortunately that's close but doesn't quite work. Its reflecting the image while it rotates it. You could fix that though:

Instead of placing the co-ordinates in their opposite (X in Y and Y in X), you have to store them in a different order.

Think about the problem. After a 90' clockwise rotation, the co-ordinates (0,0) (0,HEIGHT) should become (0, HEIGHT), (WIDTH, 0) right?

So instead of:

starting_pixel = photo.getPixel(col,row);
rotated_copy.setPixel(row, col, starting_pixel);

you need something like

starting_pixel = photo.getPixel(col,row);
rotated_copy.setPixel(photo.getWidth() - row, col, starting_pixel);

Upvotes: 0

Maciej Stachowski
Maciej Stachowski

Reputation: 1728

public static Photograph rotated(Photograph photo) {
    Photograph rotated_copy = new Photograph(photo.getHeight(), photo.getWidth());
    Pixel starting_pixel = photo.getPixel(0,0);

    for(int col = 0; col < photo.getWidth(); col++){
        for(int row = 0; row = photo.getHeight(); row++){
            starting_pixel = photo.getPixel(col,row);
            rotated_copy.setPixel(photo.getHeight() - row - 1, col, starting_pixel);
        }
    }
    return rotated_copy;
}

I think.

Upvotes: 1

Related Questions