gpt4 book ai didi

c++ - 在 C++ 中使用 CGImageDestinationCreateWithURL 创建 CGImageDestinationRef 返回 NULL

转载 作者:行者123 更新时间:2023-11-30 02:22:38 49 4
gpt4 key购买 nike

我尝试使用某些 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;
}

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

最佳答案

找到解决方案。

似乎 baseImageOutput 需要预先添加 file:// 以便最终的 url 有效,因此我们有

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

而不是

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

关于c++ - 在 C++ 中使用 CGImageDestinationCreateWithURL 创建 CGImageDestinationRef 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032135/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com