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;
}
@notedit
Copy link

notedit commented Jul 5, 2014

this does not work, i just got black image

@vikram123456
Copy link

@sakrist: Thank You so Much.. This above code worked so well for me... I would love to thank u once again because I passed 2 days for getting UIImage from GlImage

@sakrist
Copy link
Author

sakrist commented Feb 10, 2015

@notedit It could because you need another settings for CGDataProvider or in glReadPixels, or even something else. Debug and check each setting/parameter. For @vikram123456 it works and for me too, so look in your code.

@arthabus
Copy link

For ios 7+ one can use the following snippet:
UIGraphicsBeginImageContext(self.view.frame.size);
[self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

@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