【问题标题】:Creating a CGImageDestinationRef with CGImageDestinationCreateWithURL in C++ returns NULL在 C++ 中使用 CGImageDestinationCreateWithURL 创建 CGImageDestinationRef 返回 NULL
【发布时间】:2017-10-31 09:39:56
【问题描述】:

我正在尝试使用某些 OSX 框架中可用的方法为我在 C++ 中设置的 macOS 10.13 的每个监视器截取屏幕截图,但使用 CGImageDestinationCreateWithURL 创建 CGImageDestinationRef 目标返回 NULL 我不知道我做错了什么。

我认为我遇到的问题是:

CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);

我使用的代码如下:

ma​​in.cpp:

#include <iostream>
#include <string>
#include <QuartzCore/QuartzCore.h>
#include <CoreServices/CoreServices.h>
#include <ImageIO/ImageIO.h>

int main(int argc, const char * argv[]) {
    std::string baseImageOutput = "/Users/bogdan/Desktop";
    std::string pathSeparator = "/";
    std::string baseImageName = "image-";
    std::string imageExtension = ".png";

    CGDisplayCount displayCount;
    CGDirectDisplayID displays[32];

    // grab the active displays
    CGGetActiveDisplayList(32, displays, &displayCount);

    // go through the list
    for (int i = 0; i < displayCount; i++) {
        std::string imagePath = baseImageOutput + pathSeparator + baseImageName + std::to_string(i) + imageExtension;
        const char *charPath = imagePath.c_str();

        CFStringRef imageOutputPath = CFStringCreateWithCString(kCFAllocatorDefault, charPath, kCFURLPOSIXPathStyle);
        // make a snapshot of the current display
        CGImageRef image = CGDisplayCreateImage(displays[i]);

        CFURLRef url = CFURLCreateWithString(kCFAllocatorDefault, imageOutputPath, NULL);

        // The following CGImageDestinationRef variable is NULL
        CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);

        if (!destination) {
            std::cout<< "The destination does not exist: " << imagePath << std::endl;
            CGImageRelease(image);
            return 1;
        }

        CGImageDestinationAddImage(destination, image, NULL);

        if (!CGImageDestinationFinalize(destination)) {
            std::cout << "Failed to write image to the path" << std::endl;;
            CFRelease(destination);
            CGImageRelease(image);
            return 1;
        }

        CFRelease(destination);
        CGImageRelease(image);
    }

    std::cout << "It Worked. Check your desktop" << std::endl;;
    return 0;
}

我是否正确地创建了目的地?

【问题讨论】:

    标签: c++ macos quartz-core core-services


    【解决方案1】:

    找到了解决办法。

    看来baseImageOutput 需要在file:// 前面加上,这样最终的网址才有效,所以我们有

    std::string baseImageOutput = "file:///Users/bogdan/Desktop";
    

    代替

    std::string baseImageOutput = "/Users/bogdan/Desktop";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 2012-05-09
      • 2017-03-28
      • 2011-06-15
      • 1970-01-01
      相关资源
      最近更新 更多