Objective: I want to periodically make a window screenshot in OSX.
Following the Apple guides i've managed to build simple working code which captures window content very well. However, the problem is that approximately 1 of 50 pictures gets distorted for some reason.
I'm using CGWindowListCreateImage function in order to periodically capture window content, but it keeps producing garbage from time to time.
this is my simple code:
CGImageRef img = CGWindowListCreateImage(CGRectNull,
kCGWindowListOptionIncludingWindow,
wc->window.window_id, wc->image_option);
if (!img)
return;
char path_str[1024];
snprintf(path_str, 1023, "/tmp/obs/image%llu.png", ts);
// here is just output image to file "as is"
CFURLRef path =
CFURLCreateWithFileSystemPath(NULL,
__CFStringMakeConstantString(path_str),
kCFURLPOSIXPathStyle, false);
// file/format to save pixels to
CGImageDestinationRef destination =
CGImageDestinationCreateWithURL(
path, CFSTR("public.png"), 1, NULL); //[4]
// add our captured pixels
CGImageDestinationAddImage(destination, img, nil);
// generate the image
if (!CGImageDestinationFinalize(destination)) {
printf("Failed to finalize\n");
}
I ran test for different apps and windows, so result looks like this:
A good picture (what i expect from code above)
Broken picture (such picture is being captured with chance ~ 1/50)
What i already tried:
- to play with parameter CGWindowImageOption
- to use CGWindowListCreateImageFromArray instead
- to output image to the screen, i saw the same results.
build up CGImageRef upon on file, instead of capturing using CGWindowListCreateImage - works ok.
Used config:
- macOS 10.13.6
- XQuartz 2.7.11
- CoreGraphics 2.0
At this point i'm guessing CGWindowListCreateImage is buggy or something. Did anyone see something similar?