Dev Guy
Dev Guy

Reputation: 33

Get RGB of a pixel in stb_image

I'm created and loaded this image:

int x, y, comps;
unsigned char* data = stbi_load(".//textures//heightMapTexture.png", &x, &y, &comps, 1);

Now, how do i get a RGB of a certain pixel of this image?

Upvotes: 3

Views: 11957

Answers (1)

johan d
johan d

Reputation: 2863

You are using the 8-bits-per-channel interface. Also, you are requesting only one channel (the last argument given to stbi_load). You won't obtain RGB data with only one channel requested.

If you work with rgb images, you will probably get 3 or 4 in comps and you want to have at least 3 in the last argument.

The data buffer returned by stbi_load will containt 8bits * x * y * channelRequested , or x * y * channelCount bytes. you can access the (i, j) pixel info as such:

unsigned bytePerPixel = channelCount;
unsigned char* pixelOffset = data + (i + x * j) * bytePerPixel;
unsigned char r = pixelOffset[0];
unsigned char g = pixelOffset[1];
unsigned char b = pixelOffset[2];
unsigned char a = channelCount >= 4 ? pixelOffset[3] : 0xff;

That way you can have your RGB(A) per-pixel data.

Upvotes: 16

Related Questions