Cocoa 是否将CGImageRef保存到png文件?

Cocoa 是否将CGImageRef保存到png文件?,cocoa,png,core-graphics,cgimage,Cocoa,Png,Core Graphics,Cgimage,在Cocoa应用程序中,我从磁盘加载一个.jpg文件,并对其进行操作。现在需要将其作为.png文件写入磁盘。你怎么能做到 谢谢你的帮助 创建一个CGImageDestination,将kuttypeppng作为要创建的文件类型传递。添加图像,然后确定目标。使用CGImageDestination并传递kuttypeppng是正确的方法。下面是一个简短的片段: @import MobileCoreServices; // or `@import CoreServices;` on Mac @imp

在Cocoa应用程序中,我从磁盘加载一个.jpg文件,并对其进行操作。现在需要将其作为.png文件写入磁盘。你怎么能做到


谢谢你的帮助

创建一个
CGImageDestination
,将
kuttypeppng
作为要创建的文件类型传递。添加图像,然后确定目标。

使用
CGImageDestination
并传递
kuttypeppng
是正确的方法。下面是一个简短的片段:

@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
CoreServices
(或iOS上的
MobileCoreServices
)添加到项目中,并包含标题


如果您使用的是iOS,不需要在Mac上运行的解决方案,您可以使用更简单的方法:

// `image` is a CGImageRef
// `path` is a NSString with the path to where you want to save it
[UIImagePNGRepresentation([UIImage imageWithCGImage:image]) writeToFile:path atomically:YES];

在我的测试中,ImageIO方法比我的iPhone 5s上的UIImage方法快约10%。在模拟器中,UIImage方法更快。如果您真正关心性能,可能值得在设备上针对您的特定情况进行测试。

下面是一个对macOS友好的Swift 3&4示例:

@discardableResult func writeCGImage(_ image: CGImage, to destinationURL: URL) -> Bool {
    guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypePNG, 1, nil) else { return false }
    CGImageDestinationAddImage(destination, image, nil)
    return CGImageDestinationFinalize(destination)
}

伊万塞拉斯:如果你想要一个更具体的答案,你应该问一个更具体的问题(你应该作为一个单独的问题来问)。只是一个便条。我们必须添加
ImageIO.framework
来引用这些功能,甚至文档中说它位于
ApplicationServices/ImageIO
@Eonil:这取决于您为哪个平台构建。Cocoa Touch没有伞形框架,因此在构建iOS时,您确实需要直接链接到ImageIO。在为Mac OS X构建时,您可以链接到应用程序服务,并获取其中的所有内容。请参阅我的答案以获取这样做的示例。