Skip to content

Instantly share code, notes, and snippets.

@robert-wallis
Created March 1, 2013 08:43
Show Gist options
  • Save robert-wallis/5063309 to your computer and use it in GitHub Desktop.
Save robert-wallis/5063309 to your computer and use it in GitHub Desktop.
Capture the raw screen pixels in OSX. Then saves to a file for debugging.
void captureScreen()
{
CGImageRef image_ref = CGDisplayCreateImage(CGMainDisplayID());
CGDataProviderRef provider = CGImageGetDataProvider(image_ref);
CFDataRef dataref = CGDataProviderCopyData(provider);
size_t width, height;
width = CGImageGetWidth(image_ref);
height = CGImageGetHeight(image_ref);
size_t bpp = CGImageGetBitsPerPixel(image_ref) / 8;
uint8 *pixels = malloc(width * height * bpp);
memcpy(pixels, CFDataGetBytePtr(dataref), width * height * bpp);
CFRelease(dataref);
CGImageRelease(image_ref);
FILE *stream = fopen("/Users/robert/Desktop/screencap.raw", "w+");
fwrite(pixels, bpp, width * height, stream);
fclose(stream);
free(pixels);
}
@MKesenheimer
Copy link

Thanks for the code. But how do I compile it, which headers do I have to include? Can you give me an example please?
Can I compile the program in command line?

@kwhat
Copy link

kwhat commented Dec 30, 2020

Anyone looking to capture part of the screen, replace CGImageRef image_ref = CGDisplayCreateImage(CGMainDisplayID()); with the following:

    CGRect rect = CGRectMake(x, y, width, height);
    CGImageRef image_ref = CGDisplayCreateImageForRect(kCGDirectMainDisplay, rect);

@robert-wallis
Copy link
Author

I like your version @kwhat https://github.com/kwhat/libscreencapture/blob/master/src/darwin/screen_capture.c awesome you are making a multi-platform library!!!

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