Taylor
Taylor

Reputation: 316

Fast/Optimized way to flip an RGBA image vertically

I have a byte[] for a RGBA array. I have the following method that flips the image vertically:

    private byte[] FlipPixelsVertically(byte[] frameData, int height, int width)
    {
        byte[] data = new byte[frameData.Length];

        int k = 0; 
        for (int j = height - 1; j >= 0 && k < height; j--)
        {
            for (int i = 0; i < width * 4; i++)
            {
                data[k * width * 4 + i] = frameData[j * width * 4 + i];
            }
            k++;
        }

        return data;
    }

The reason I am creating new byte[] is because I do not want to alter the contents of frameData, since the original info will be used elsewhere. So for now, I just have a nested for loop that copies the byte to the proper place in data.

As height and width increase, this will become an expensive operation. How can I optimize this so that the copy/swap is faster?

Upvotes: 0

Views: 446

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 134075

Using Buffer.BlockCopy:

private byte[] FlipPixelsVertically(byte[] frameData, int height, int width)
{
    byte[] data = new byte[frameData.Length];

    int k = 0;

    for (int k = 0; k < height; k++)
    {
        int j = height - k - 1;
        Buffer.BlockCopy(
            frameData, k * width * 4,
            data, j * width * 4,
            width*4);
    }

    return data;
}

Upvotes: 1

Related Questions