简体   繁体   中英

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 i'm get a RGB of a certain pixel of this image?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM