Skip to content

Instantly share code, notes, and snippets.

@sakrist
Last active August 28, 2020 06:21
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakrist/3761227 to your computer and use it in GitHub Desktop.
Save sakrist/3761227 to your computer and use it in GitHub Desktop.
Getting screenshot on iOS OpenGL ES
- (UIImage*) takePicture {
int s = 1;
UIScreen* screen = [UIScreen mainScreen];
if ([screen respondsToSelector:@selector(scale)]) {
s = (int) [screen scale];
}
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
int width = viewport[2];
int height = viewport[3];
int myDataLength = width * height * 4;
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
for(int y1 = 0; y1 < height; y1++) {
for(int x1 = 0; x1 <width * 4; x1++) {
buffer2[(height - 1 - y1) * width * 4 + x1] = buffer[y1 * 4 * width + x1];
}
}
free(buffer);
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, releaseData);
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * width;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGImageRef imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
CGColorSpaceRelease(colorSpaceRef);
CGDataProviderRelease(provider);
UIImage *image = [ UIImage imageWithCGImage:imageRef scale:s orientation:UIImageOrientationUp ];
return image;
}
@namiazad
Copy link

I also got a black image because glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer) fills buffer with zeroes

@hardikamal
Copy link

@namiazad Were you able to solve the issue? Even I am getting empty buffer

@espadandy
Copy link

This works great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment