Использование CGImageDestination
и пропуск kUTTypePNG
- правильный подход. Вот быстрый фрагмент:
@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
(или MobileCoreServices
на iOS) в ваш проект и включить заголовки.
Если вы работаете на 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 был примерно на 10% быстрее, чем подход UIImage на моем iPhone 5s. В симуляторе подход UIImage был быстрее. Вероятно, стоит проверить каждую из них на вашей конкретной ситуации на устройстве, если вы действительно обеспокоены производительностью.