4

我正在尝试加载图像文件并将其用作立方体的纹理。我正在使用 SDL_image 来做到这一点。

原始图像

我使用这张图片是因为我发现它有各种文件格式(tga、tif、jpg、png、bmp)

编码 :

SDL_Surface * texture;

//load an image to an SDL surface (i.e. a buffer)

texture = IMG_Load("/Users/Foo/Code/xcode/test/lena.bmp");

if(texture == NULL){
    printf("bad image\n");
    exit(1);
}

//create an OpenGL texture object 
glGenTextures(1, &textureObjOpenGLlogo);

//select the texture object you need
glBindTexture(GL_TEXTURE_2D, textureObjOpenGLlogo);

//define the parameters of that texture object
//how the texture should wrap in s direction
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//how the texture should wrap in t direction
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
//how the texture lookup should be interpolated when the face is smaller than the texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//how the texture lookup should be interpolated when the face is bigger than the texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

//send the texture image to the graphic card
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->w, texture->h, 0, GL_RGB, GL_UNSIGNED_BYTE, texture-> pixels);

//clean the SDL surface
SDL_FreeSurface(texture);

代码编译没有错误或警告!

我已经厌倦了所有文件格式,但这总是会产生丑陋的结果:

结果

我正在使用:SDL_image 1.2.9 和 SDL 1.2.14,XCode 3.2 在 10.6.2 下

有谁知道如何解决这个问题?

4

3 回答 3

11

图像失真的原因是它不是您指定的 RGBA 格式。检查texture->format以找出它所在的格式并选择GL_代表该格式的适当常量。(或者,自己将其转换为您选择的格式。)

于 2009-11-12T23:34:22.323 回答
3

我认为grayfade有正确的答案,但您应该注意的另一件事是需要锁定表面。情况可能并非如此,因为您正在使用内存中的表面,但通常您需要先锁定表面,然后才能使用SDL_LockSurface(). 例如:

bool lock = SDL_MUSTLOCK(texture);
if(lock)
    SDL_LockSurface(texture);  // should check that return value == 0
// access pixel data, e.g. call glTexImage2D
if(lock)
    SDL_UnlockSUrface(texture);
于 2009-11-12T23:47:29.133 回答
0

如果你有一个 alpha 通道,每个像素都是 4 个无符号字节,如果你没有,它是 3 个无符号字节。此图像没有透明度,当我尝试保存它时,它是 .jpg。

改变

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 纹理->w, 纹理->h, 0, GL_RGB, GL_UNSIGNED_BYTE, 纹理-> 像素);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 纹理->w, 纹理->h, 0, GL_RGB, GL_UNSIGNED_BYTE, 纹理-> 像素);

那应该解决它。

对于具有 Alpha 通道的 .png,请使用

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 纹理->w, 纹理->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 纹理-> 像素);

于 2010-04-02T07:01:18.787 回答