index
of pixel(x, y) = (y * imageWidth + x) * numComponents
Image data is stored in row major order starting with the upper left
pixel of the image. This means the image data stores all of the
pixels in the first row from left to right followed by all the pixels
in the second row from left to right, etc through all the rows in the
image. Hence to find the pixel location we multiply the row of
the pixel we want by the width of the image and then add the column of
the desired pixel. This will give us the index of the pixel in
the image data array. There's one catch though, each pixel in the
image has multiple components (red, blue, green, etc), hence each pixel
is using multiple slots in the array so we need to multiply our pixel
index by the number of components per pixel to get the actual index
into the image data. All TargaImage
images have four components (red, green, blue, alpha) so for any image
data loaded with the TargaImage
class we'll always be multiplying by four to get the actual index into
the image array.
The above code uses this formula to calculate a pointer to both the
source and destination pixels. It then iterates through each of
the four components of the pixels, replacing the destination pixels's
component with the corresponding component of the source pixel.