Home > front end >  Why doesn't my code flip image horizontally?
Why doesn't my code flip image horizontally?

Time:06-01

public void flipImageHorizontally(){

        this.redisplayImage();

        for(int x = 0; x < this.image.length; x  )
        for(int y = 0; y < this.image[0].length; y  ){
        this.image[x][y] = this.image[x][this.image[0].length - 1 - y];
        }
    }

The code runs but it doesn't perform the action intended. It is supposed to flip the image horizontally but instead, it only flips half of the image.

CodePudding user response:

Let's say you have an image two pixels wide and one pixel high:

1 2

After the first iteration of your loop, the end pixel will be swapped to the beginning (image[0][0] = image[0][2 - 1 - 0];):

2 2

But now you lost the original value of image[0][0]! So when you do the swap image[0][1] = image[0][2 - 1 - 1];, you are copying the second half of the image back to itself.

The right answer is to use a buffer so you don't overwrite the swap:

for(int y = 0; y < this.image[0].length / 2; y  ) {
    int buffer = this.image[x][y];
    this.image[x][y] = this.image[x][this.image[0].length - 1 - y];
    this.image[x][this.image[0].length - 1 - y] = buffer;
}

Integer truncation ensures that this.image[0].length / 2 is an efficient bound. For even numbers, you iterate exactly the first half. For odd numbers, you iterate the first half, not including the middle pixel. That's a good thing, because the middle does not need to be swapped.

CodePudding user response:

You need to iterate up to the middle, and swap pixels that are on the left with pixels that are on the right. Otherwise you end up overwriting your changes.

public void flipImageHorizontally() {
    this.redisplayImage();

    for(int x = 0; x < this.image.length; x  ) {
        for(int y = 0; y < this.image[x].length / 2; y  ) {
            int pixel = this.image[x][y]; // assuming int
            
            this.image[x][y] = this.image[x][this.image[x].length - 1 - y];
            this.image[x][this.image[x].length - 1 - y] = pixel;
        }
    }
}

In this code

  1. the pixel variable temporarily holds the value on the left;
  2. the value on the left gets assigned the value on the right;
  3. the value on the right gets the value that was originally on the left (i.e. whatever is in pixel).

Notes:
  • I maintained your naming of x and y, even though it's counter-intuitive because it makes it look like you're performing a vertical flip instead of a horizontal one.
  • I don't know the data type of the array; I assumed int, but it might be a float array, Pixel objects, or something else.
  • I don't know what this.redisplayImage(); is supposed to do, and whether it's in the right location.
  • Related