简体   繁体   中英

2D array and creating a mirror of an image

I'm supposed to create an image editor using 2D arrays. For this part I'm supposed to create code that creates a mirror of the image by flipping it left to right. Instead I'm flipping it upside down. What am I doing wrong?

public void mirror() {
    // TODO Auto-generated method stub
    int[] img;
    int left = 0, right = data.length -1;
    while (right >= left) {
        img = data[left];
        data[left++] = data[right];
        data[right--] = img;
    }       
}

Multiple Problems: 1. You're using a 1D Array. 2. data.length on 1d array gives you number of rows. 3. Now when you use data.length for reversing, you end up revering rows instead of columns in 2d array. Hence your logically incorrect output.

Use mirror method should be something like this -

public int[][] mirror(int[][] original) {
     int[][] mirror = original;
     for (int i=0; i<original.length; i++) {
         original[i] = reverseArray(original[i]);
     }
     return mirror;
}


public int[] reverseArray(int[] array) {
    for (i = 0; i < array.length / 2; i++) {
        int temp = array[i];
        array[i] = array[array.length - 1 - i];
        array[array.length - 1 - i] = temp;
    }
    return array;
}

The problem is you were just mirroring the arrays that made up the matrix, rather than reversing the order of the arrays. Assuming data was in fact a 2D array to begin with, this should work for you.

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

A more simple way than the other answers in my opinion:

int[][] mirrored = new int[data.length][data[0].length];
for (int i = 0; i < data.length; i++) {
    for (int j = 0; j < data[i].length; j++) {
        mirrored[i][data[i].length - j - 1] = data[i][j];
    }
}

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