openglpixelgetpixel

why is the pixel coordinate in x,y plane x + y*width?


I'm currently learning about opengl and I don't understand how the pixel coordinate works.

First, the x, y coordinates would go into a double loop until x < width and y < height, and within that loop, the pixel coordinate is equal to x + y*width and I don't understand why this is so.


Solution

  • This results from how the pixels are stored in memory.

    Here's a sketch of the pixels:

    |-------width-------|
    + + + + + + + + + + +  <--- row_0
    + + + + + + + + + + +  <--- row_1
    + + + + + + + + + + +  <--- row_2
           .....
    + + + + + + + + + + +  <--- row_n
    0 1 ...         ... m  columns
    

    This is laid out in memory in row major mode:

    [row_0,row_1,...row_n]
    

    Since each row has width pixels, then the (x,y) pixel, meaning the x-th column in y-th row, is stored in position x+y*width.