目标:我想定期在OSX中制作一个窗口截图。
按照Apple指南,我设法构建了可以很好地捕获窗口内容的简单工作代码。但是,问题在于50张图片中大约有1张由于某种原因而失真。
我正在使用 CGWindowListCreateImage 函数来定期捕获窗口内容,但是它会不时产生垃圾。
这是我的简单代码:
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");
}
我针对不同的应用程序和窗口进行了测试,因此结果如下:
我已经尝试过的:
在文件上建立 CGImageRef ,而不是使用 CGWindowListCreateImage 捕获-可以。
使用的配置:
在这一点上,我猜测 CGWindowListCreateImage 有问题。有人看到类似的东西吗?