简体   繁体   中英

How to load a .pgm texture file into openGL

So far I have this code:

ifstream textureFile;
char* fileName="BasketBall.pgm";
textureFile.open(fileName, ios::in);
if (textureFile.fail()) {
    displayMessage(ERROR_MESSAGE, "initTexture(): could not open file %s",fileName);
}
skipLine(textureFile); // skip the "P2" line in the Net.pgm file.
textureFile >> textureWidth; // read in the width
textureFile >> textureHeight; // read in the height
int maxGrayScaleValue;
textureFile >> maxGrayScaleValue; // read in the maximum gray value (255 in this case)
texture = new GLubyte[textureWidth*textureHeight];

int grayScaleValue;
for (int k = 0; k < textureHeight; k++) {
    for(int l = 0; l < textureWidth; l++) {
        textureFile >> grayScaleValue;
        texture[k * textureWidth + l]=(GLubyte) grayScaleValue;
    }
}
textureFile.close();

glBindTexture(GL_TEXTURE_2D, texName);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 
            0, GL_RGBA, GL_UNSIGNED_BYTE, texture);

But when I try to run it after building successfully, it just says that my project has "stopped working".

This is most likely caused by the fact that you are trying to load a greyscale image into an RGBA container.

There are two ways I can think of to try and fix your problem:

The first is to make texture 3 times bigger and load the greyscale value into 3 consecutive spaces. So:

texture = new GLubyte[textureWidth*textureHeight*3];

and

for (int k = 0; k < textureHeight; k++) {
    for(int l = 0; l < textureWidth; l+=3) {
        textureFile >> grayScaleValue;
        texture[k * textureWidth + l]=(GLubyte) grayScaleValue;
        texture[k * textureWidth + l + 1]=(GLubyte) grayScaleValue;
        texture[k * textureWidth + l + 2]=(GLubyte) grayScaleValue;
    }
}

and

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 
        0, GL_RGB, GL_UNSIGNED_BYTE, texture);

The second is to try it with only a single channel so:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 
        0, GL_RED, GL_UNSIGNED_BYTE, texture);

Other than that, I suggest using a debugger and breakpoints to step through your code and find out where you are crashing, but as I mentioned above, it's probable becuase you are passing a single channel texture into a container which is expecting 4 channels.

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