首页 > 解决方案 > CGWindowListCreateImage 产生损坏的图像

问题描述

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

我对不同的应用程序和窗口进行了测试,所以结果如下所示:

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

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

残破的照片(这样的照片是偶然拍到的~1/50)

残破的图片(这样的图片被偶然捕获〜1/50)

我已经尝试过的:

在这一点上,我猜CGWindowListCreateImage是错误的或什么的。有没有人看到类似的东西?

标签: macoscocoacore-graphicsxquartz

解决方案


推荐阅读