如何更改ios中用于OpenGL的图像格式? (将图像加载到OpenGL ES 2.0)
问题描述:
我正在通过相机拍摄照片,我想更改其格式以使其与OpenGL ES 2.0纹理兼容。如何更改ios中用于OpenGL的图像格式? (将图像加载到OpenGL ES 2.0)
首先,我明白了,我调整它的大小(使它2的幂以防万一):
UIImage *newImage = [self imageWithImage:imgName scaledToSize:CGSizeMake(100, 144)];
然后我改变从JPEG格式(我认为它的iPhone的默认格式) PNG:
NSData *test = UIImagePNGRepresentation(newImage);
UIImage *converted = [[UIImage alloc] initWithData:test];
最后我创造我的背景,并吸引到它:
GLubyte * spriteData = (GLubyte *) calloc(width*height*4, sizeof(GLubyte));
CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width*4,
CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
CGContextDrawImage(spriteContext, CGRectMake(0, 0, width, height), spriteImage);
CGContextRelease(spriteContext);
,我可以再补充它在这之后的开放GL缓冲区,不幸的是它不工作(只有黑色出现),我很确定它是因为图像格式,因为如果我做了与另一个图像,我已经知道它的作品,然后一切顺利进行完全相同的过程。
我做了一些研究,它可能与我的图像中的颜色深度有关,因为我需要每像素4位渲染opengl纹理(4,4,4,4)。
内部格式:RGBA,外部格式:RGBA,类型:无符号字节,每像素字节:4
所以我的问题是,如何改变从它的方案,我需要什么深度PNG文件?
PD:如果有人知道以不同的方式将图像加载到opengl中,请告诉我!
谢谢!
答
我的设置纹理的方法。我认为全部清楚,如果不是 - 提问
- (GLuint)setupTexture:(NSString *)fileName {
CGImageRef spriteImage = [UIImage imageNamed:fileName].CGImage;
if (!spriteImage) {
NSLog(@"Failed to load image %@", fileName);
exit(1);
}
size_t width = CGImageGetWidth(spriteImage);
size_t height = CGImageGetHeight(spriteImage);
GLubyte * spriteData = (GLubyte *) calloc(width*height*4, sizeof(GLubyte));
CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width*4, CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM (spriteContext, 0, height);
CGContextScaleCTM (spriteContext, 1.0, -1.0);
CGContextDrawImage(spriteContext, CGRectMake(0, 0, width, height), spriteImage);
CGContextRelease(spriteContext);
GLuint texName;
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glGenTextures(1, &texName);
glBindTexture(GL_TEXTURE_2D, texName);
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_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);
free(spriteData);
return texName;
}
感谢您的快速回复。我试过你的方法,它只适用于已定义的纹理。问题是我试图在iphone上使用相机“纹理化”物体,所以我必须从相机中取出输入。我有一个图像,我以jpeg和png格式在我的屏幕上显示它,所以我知道它的工作原理,我也尝试调整它的大小。但是当我尝试使用你的方法显示它时,我得到了完全相同的结果(即纹理应该是黑色),当我想创建我的纹理时遇到了类似的问题,问题在于颜色深度。有任何想法吗? =( – Pochi 2012-01-12 08:52:10
)事实证明,问题出在我创建的图像大小上。 This line UIImage * newImage = [self imageWithImage:imgName scaledToSize:CGSizeMake(100,144)]; 创建2图像的非幂次,并且对于iPhone的纹理,你需要2图像的力量(256x256,256x512等)。Thx for ur help。 – Pochi 2012-01-16 09:29:58
yea!:)我想你知道这件事。 – SAKrisT 2012-01-16 11:00:47