# How does Texture2D.GetData return coloured pixels?

I'm trying to work out how the pixels are stored in the returned array but I'm not having a lot of luck (and thus my calculations don't seem to be working).

I realize that the pixels are stored in one long continuous array but are the pixels grabbed width first or height first? I've tried drawing out the "pixels" of a texture on paper to calculate where the pixels should be based on the single array but I'm not getting expected results.

My assumption is the following:

Assuming I am using i to specify rows and j to specify columns that any given pixel in a 2D texture can be calculated by the sum of i * j or is this incorrect?

• Try i*width + j – Nathan Reed Aug 28 '14 at 7:00
• Im not an xna developer, but does GetData return an array of 'pixels' or an array of bytes? – RamblingMad Aug 28 '14 at 9:39
• Its a generic, so it returns an array of objects of the specified type. msdn.microsoft.com/en-us/library/bb197089.aspx – Seta Aug 28 '14 at 10:30

## 1 Answer

The answer to this question here should help explain how to use the GetData function.

Basically, the data is stored in the return array from the GetData call is formed by reading the 2D texture from left to right, top to bottom, transforming it as follows:

AAAA
BBBB  => AAAABBBBCCCCDDDD
CCCC
DDDD


To determine where a given pixel in the 1D array is, we use the index calculation of i + (j * width) should return the correct pixel at any given point.

Your assumptions is almost correct, you are just forgetting to take the width into account. Basically, multiply the Y coord (your j value) by the width of the Texture to select the correct start of the index block containing your pixel, then add the X coord (your i value) to select the correct pixel from that block.

In the sample above, assuming we want the value at (1,2), we have the following equation.

v = i + (j * width)
v = 1 + (2 * 4)
v = 1 + 8
v = 9
item at offset 9 = C


On 2nd though, that first link probably isn't the best, its just the first one I found with the required math. Here's another one that describes (sortof) how to use it.

• So are you saying the X position is the row of the pixel (in the texture itself) and (Y * width) is the Y co-ordinate of the pixel in the 2D Texture? – Scott Aug 28 '14 at 8:16
• I've updated my answer, hopefully it clears things up a bit. – Seta Aug 28 '14 at 9:33