CGWindowListCreateImage产生损坏的图像

时间:2018-09-30 21:44:54

标签: macos cocoa core-graphics xquartz

目标:我想定期在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");
}

我针对不同的应用程序和窗口进行了测试,因此结果如下:

一张好照片(我对上面的代码有什么期望)

A good picture (what i expect from code above)

图片破损(此类图片的拍摄机会约为1/50)

Broken picture (such picture is being capture with chance ~ 1/50)

我已经尝试过的:

  • 使用参数 CGWindowImageOption
  • 改为使用 CGWindowListCreateImageFromArray
  • 将图像输出到屏幕上,我看到了相同的结果。
  • 在文件上建立 CGImageRef ,而不是使用 CGWindowListCreateImage 捕获-可以。

    使用的配置:

    • macOS 10.13.6
    • XQuartz 2.7.11
    • CoreGraphics 2.0

在这一点上,我猜测 CGWindowListCreateImage 有问题。有人看到类似的东西吗?

0 个答案:

没有答案