I'm dealing with an image that is stored in a 2D array, but the image is upside down. What I'm trying to do is flip it vertically. I need to swap the first row and the last row, the second row and the second to last row, and so on. Here is what I tried:
public void mirror() {
for (int i = 0; i < height; i++) {
int[] firstRow = imageData[i];
int[] secondRow = imageData[height - 1 - i];
int[] tempRow = firstRow;
firstRow = secondRow;
secondRow = tempRow;
imageData[i] = secondRow;
imageData[height - 1 - i] = firstRow;
This runs without any errors, but the picture doesn't change at all.
The height variable is the height of imageData[][] which is the 2D array where the picture is stored.
You're swapping the rows twice .
for (int i = 0; i < height; i++)
Once i
reaches values greater than height / 2
, you start to access rows that have already been swapped, and swap them back to their original positions. To prevent this, the loop should stop in the middle, ie when i
reaches height / 2
.
You also have a slight logic error in your algorithm; you already assigned the value of secondRow
to firstRow
and vice versa, so those respective values are what should be the elements of imageData[i]
and imageData[height - 1 - i]
.
imageData[i] = firstRow;
imageData[height - 1 - i] = secondRow;
Your "swap" is a no-op. Ignoring secondRow
for a minute:
int[] firstRow = imageData[i];
int[] tempRow = firstRow;
secondRow = tempRow; // == firstRow
imageData[i] = secondRow; // == tempRow == firstRow !
and on top of that you're (not) doing the swaps twice over.
Instead, try this:
for (int i = 0; i < height / 2; ++i) {
int[] tempRow = imageData[i];
imageData[i] = imageData[height - i - 1];
imageData[height - i - 1] = tempRow;
}
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.