使用java(netbeans)将图片旋转90度

时间:2014-02-11 00:50:40

标签: java image image-processing

我无法弄清楚如何设置newPixels [row]和[col]以使新图片正确旋转原件。我不断收到过错的错误。你能看到我在哪里出错吗?

/** 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;
    }

1 个答案:

答案 0 :(得分:0)

你有太多的循环。它比你想要的更简单。只需按行/列迭代所有像素,然后将行分配给新列,将列分配给新行 - 如下所示:

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;
 }