简体   繁体   中英

rotate a picture 90 degrees using java (netbeans)

I cannot figure out how to set the newPixels [row] and [col] in a way for the new picture to be a correct rotation of the original. I keep getting a over bound error. Can you see where I went wrong here?

/** Rotate the image
*/
    public void rotate()
   {
        int newWidth = height;
        int newHeight = width;  
        int [] [] newPixels = new int [newHeight] [newWidth];
        for (int row = 0; row < height; row ++)
            for (int row2 = 0; row2 < newHeight; row2 ++)
                for (int col = 0; col < width; col ++)
                for (int col2 = 0; col2 < newWidth; col2 ++)  
                {newPixels[row2][col2] = pixels[width-col-1][height-row-1];}

    width=newWidth;
    height=newHeight;
    pixels = newPixels;
    }

You have too many loops going on. It is simpler than you are making it out to be. Just iterate through all the pixels by row/col, and assign the row to new column and the column to new row - like this:

public void rotate()
{
    int [] [] newPixels = new int [width] [height];
    for (int row = 0; row < height; row ++)
        for (int col = 0; col < width; col ++)
            newPixels[col][row] = pixels[row][col]; // Assign to rotated value.

    // Swap width and height values.
    int tmp = width;
    width = height;
    height = tmp;
    pixels = newPixels;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM