Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I know that there is the Texture.getTextureData() method, and that it returns a byte[], but I have no idea how I could use this data to find the color data at a specific pixel.

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

I'm not too familiar with Slick2D, but assuming it's sending back uncompressed data like most other methods of this type are, the byte array just represents color channel data packed together. Each color consists of a Red, Green, Blue, and sometimes Alpha channel. Typically the order of these channels are RGBA, but it's possible that the orders are flipped, I've seen ARGB and BGRA before. So the byte array is going to look something like R, G, B, A, R, G, B, A.... If you wanted to figure out which order it returns (a quick search of Slick2D documentaiton doesn't find any mention of channel order), you could create an all-red or gradient transparency image and read the first few values of the byte array from the debugger.

Also note that the 2d texture has it's data unrolled so that the byte[] is a single-dimensional array. You can access the A channel of a pixel at a given location like this:

//pixel locations to look up, assume initialized and checked to be in texture bounds.
int px, py;
byte[] texData = tex.getTextureData();
byte alpha = texData[4 * (py * tex.getTextureWidth() + px) + 3];

Breaking down the last line of the example in order of operation:

py * tex.getTextureWidth() + px is the standard way of looking up a 2d index in a 1d array. This is the location of the pixel were this an array of pixels.

4 * takes the pixel location and scales it to represent the color channels. This gets you the location of the first channel of the selected pixel. (Assuming RGBA layout, this would be the red channel)

+ 3 offsets the red channel location to the alpha channel. This is assuming RGBA ordering. If it were ARGB this part isn't necessary.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.