Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I flip an image vertically in Java?

Tags:

java

I have to flip the image horizontally but when I put in my code it only flips half of so that it reflects halfway through the image. What am I doing wrong?

public static void flipVertical(Pixel[][] imageArr)
{
    int height = imageArr.length;
    int width = imageArr[0].length;

    for(int row = 0; row < height; row++)
        {
            for(int col = 0; col < width; col++)
            {
                Pixel p = imageArr[row][col];

                imageArr[height - row - 1][col] = p;
            }
        }
like image 762
Aleks Avatar asked Jul 03 '26 20:07

Aleks


1 Answers

Your code doesn't work currently because it is copying the flipped bottom half of the image into the top half without keeping the original data in the top half of the image. As such, when it processes the bottom half of the image, it is effectively copying the same data back to the bottom half again.

When you swap two values, a and b, you would need to use a temporary variable:

Pixel tmp = a;
a = b;
b = a;

If you do it like you have:

a = b;  // After, a == b and b == b.
b = a;

then the second assignment is effectively a no-op, since a's value is already b.

As such, you need to update your inner loop to:

Pixel p = imageArr[row][col];
imageArr[row][col] = imageArr[height - row - 1][col];
imageArr[height - row - 1][col] = p;

Also, the outer for loop should be:

for(int row = 0; row < height/2; row++)

Otherwise you flip the image, and then flip it back again.

like image 53
Andy Turner Avatar answered Jul 05 '26 08:07

Andy Turner