I'm trying to get the colour of a specific pixel from a specific texture using OpenGL (C++). I've been looking at glGetTexImage()
since it looks somewhat like what I want, but I can't figure out the context in which I should put it. Am I wrong? It doesn't need to be the fastest option since it's not a frame-by-frame thing; just when the game starts up.
The texture isn't going to be rendered to the screen and is just used as a way to get information. I use the following function to load the texture.
GLuint TextureUtil::loadTexture(const char* filename, int* widthVar, int* heightVar) {
unsigned char* image = SOIL_load_image(filename, widthVar, heightVar, NULL, SOIL_LOAD_RGBA);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
if (image) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, *widthVar, *heightVar, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
} else {
std::cout << "ERROR: TextureUtil.cpp - Texture loading failed." << std::endl;
}
glActiveTexture(0);
glBindTexture(GL_TEXTURE_2D, 0);
SOIL_free_image_data(image);
return texture;
}
Assuming you are interested in a pixel at coordinates column x
and row y
, then:
unsigned char* image = SOIL_load_image(filename, widthVar, heightVar, NULL, SOIL_LOAD_RGBA);
int width = *widthVar;
unsigned char* pixel = image + y * width * 4 + x * 4;
unsigned char red = pixel[0];
unsigned char green = pixel[1];
unsigned char blue = pixel[2];
unsigned char alpha = pixel[3];
Error checking of the SOIL_load_image function is left for to you to add. I would fully expect it to return nullptr if the filename didn't exist, for example.
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.