Meowzen
Meowzen

Reputation: 113

Java: rotate image 90 degrees

I'm trying to write a method to turn an image 90 degrees to the right. I already checked other posts about this topic and none of them seem to help me resolve my issue. My code seems to work on paper but I don't know why the j-unit test won't go through. Why isn't my j-unit test going through?

my code:

 /**
* intialize a picture by giving an image matrix
* @param imageMatrix two dimansionar RGBColor array
*/
public Picture(RGBColor imageMatrix[][]){
    this.width = imageMatrix.length;
    this.height = imageMatrix[0].length;
    this.imageMatrix = imageMatrix;
}

/**
 * turns this picture 90 degrees to the right
 *
 */
public void rot90DegRight(){
    int w = imageMatrix.length;
    int h = imageMatrix[0].length;
    RGBColor[][] rotatedMatrix = new RGBColor[h][w];
    for (int i = 0; i<h; i++){
        for(int j = 0; j<w; j++){
            rotatedMatrix[i][j] = imageMatrix[w-j-1][i];
        }
    }

}

here is the j-unit testcase too:

@Test(timeout=1000)
public void testRot90DegRight(){
    RGBColor[][] imageMatrix = new RGBColor[100][100];
    for (int w=0; w<100; w++){
        for (int h=0; h<100; h++){
            if ((w==20) & (h==20)){
                imageMatrix[w][h] = new RGBColor(255,255,255);
            } else {
                imageMatrix[w][h] = new RGBColor(0,0,0);
            }
        }
    }
    Picture p = new Picture(imageMatrix);
    p.rot90DegRight();
    assertTrue("The white pixel was not rotated", !(p.getImageMatrix()[20][20].isWhite()));
    assertTrue("The white pixel was not rotated", (p.getImageMatrix()[79][20].isWhite()));

}

Upvotes: 1

Views: 1118

Answers (2)

Bill Darson
Bill Darson

Reputation: 23

MikeCAT's right. It's like this (in simple terms):

Say you're trying to rotate this double array:

1 2 3 4

1 2 3 4

1 2 3 4

1 2 3 4

With your approach, after you replace [0][3] with [0][0], you end up going back to [0][3] in your loop and replacing [0][0] with [0][3]. The array will undo itself halfway through, leaving you with the same result.

Hope this helps!

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

You created rotatedMatrix and assigned some values there in rot90DegRight(), but then simply threw the result away. You will have to store the result of rotation somewhere.

Adding

this.imageMatrix = rotatedMatrix;

after the outer for loop may make it work.

Note that this will make it no longer refer to the array passed to the constructor after doing rotation.

Upvotes: 2

Related Questions