如何将CGImageRef写入png文件。 CGImageDestinationCreateWithURL返回nil

时间:2017-02-21 18:37:10

标签: objective-c macos

- (void)takeScreenShot {
    CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
    CGImageWriteToFile(screenShot, [@"~/code/screenshot.png" stringByExpandingTildeInPath]);
}

BOOL CGImageWriteToFile(CGImageRef image, NSString *path) {
    CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
    if (!destination) {
        NSLog(@"Failed to create CGImageDestination for %@", path);
        return NO;
    }

    CGImageDestinationAddImage(destination, image, nil);

    if (!CGImageDestinationFinalize(destination)) {
        NSLog(@"Failed to write image to %@", path);
        CFRelease(destination);
        return NO;
    }

    CFRelease(destination);
    return YES;
}
  

无法为其创建CGImageDestination   /用户/"用户名" /库/容器/" bundleidentifier" /Data/code/screenshot.png

所以没有返回目的地。 我最好写信给〜/ code / screenshot.png但是如果它是沙盒的话,也可以写入" sandbox"

如何将屏幕截图写入我稍后可以访问的文件?

我改编了Saving CGImageRef to a png file?

的代码

1 个答案:

答案 0 :(得分:2)

@import MobileCoreServices; // or `@import CoreServices;` on Mac
@import ImageIO;

BOOL CGImageWriteToFile(CGImageRef image, NSString *path) {
    CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
    if (!destination) {
        NSLog(@"Failed to create CGImageDestination for %@", path);
        return NO;
    }

    CGImageDestinationAddImage(destination, image, nil);

    if (!CGImageDestinationFinalize(destination)) {
        NSLog(@"Failed to write image to %@", path);
        CFRelease(destination);
        return NO;
    }

    CFRelease(destination);
    return YES;
}

您必须将ImageIO和MobileCoreServices添加到项目中,并且还必须添加标题。