Horizontal Transformation of Array (2D)

别等时光非礼了梦想. 提交于 2019-12-04 20:49:21

It is happening because you are using i instead of j. But i will not stop after halfway, but it is continued and re-swap the array.
Here is a correct code :

for (int i = 0; i < imgArray.length; i++) {
    for (int j = 0; j < imgArray[i].length / 2; j++) {
        temp = imgArray[i][j];
        imgArray[i][j] = imgArray[i][imgArray.length - 1 - j];
        imgArray[i][imgArray.length - 1 -j] = temp;
    }
}

Or if you want to swap columns, not rows :

for (int i = 0; i < imgArray.length / 2; i++) {
    for (int j = 0; j < imgArray[i].length; j++) {
        temp = imgArray[i][j];
        imgArray[i][j] = imgArray[imgArray.length - 1 - i][j];
        imgArray[imgArray.length - 1 -i][j] = temp;
    }
}

This will correctly flip the image horizontally:

public static void horizontalFlip(int[][] imgArray)
{
    int temp;
    for (int i = 0; i < imgArray.length; i++) {
        for (int j = 0; j < imgArray[i].length/2; j++) {
        temp = imgArray[i][j];
        imgArray[i][j] = imgArray[i][imgArray[i].length - 1 - j];
        imgArray[i][imgArray[i].length - 1 - j] = temp;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!