Search code examples
iosios4opengl-es-2.0

In UIImage to Texture conversion, Texture is flipped vertically


I am trying to read UIImage into the texture on iOS platform. I found the code snippet on StackOverflow that does the trick, but the problem is when I display the texture it is displayed Mirrored upside down.

int numComponents = 4;

UIImage* image = [UIImage imageNamed:@"Test.png"];
CGImageRef imageRef = [image CGImage];
int width = CGImageGetWidth(imageRef);
int height = CGImageGetHeight(imageRef);

//Allocate texture data
GLubyte* textureData = (GLubyte *)malloc(width * height * numComponents);    

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(textureData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

//texture setup
GLuint textureID;    
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &textureID);

glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureDataMirrored);   

I also tried to mirror the UIImage using following line (before reading the data) but its not working either. In fact no effect whatsoever.

image = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:UIImageOrientationUpMirrored]; 

Please let me know what am I doing wrong here. Thank you.


Solution

  • This two lines fixed the problem

    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0,height);
    CGContextConcatCTM(context, flipVertical);