H 巴斯坦,
根据您的评论:
...我想通过文档目录中的 UIImagepicker 委托方法保存设备相机返回的捕获图像...
看起来您的真正目标是将带有 EXIF 数据的图像保存到文档目录,而不是专门将 UIImage 作为带有 EXIF 数据的 NSData 对象。在这种情况下,您可以在 imagePickerController:didFinishPickingMediaWithInfo: 的实现中执行以下操作
// Get your image.
UIImage *capturedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
// Get your metadata (includes the EXIF data).
NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
// Create your file URL.
NSFileManager *defaultManager = [NSFileManager defaultManager];
NSURL *docsURL = [[defaultManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
NSURL *outputURL = [docsURL URLByAppendingPathComponent:@"imageWithEXIFData.jpg"];
// Set your compression quuality (0.0 to 1.0).
NSMutableDictionary *mutableMetadata = [metadata mutableCopy];
[mutableMetadata setObject:@(1.0) forKey:(__bridge NSString *)kCGImageDestinationLossyCompressionQuality];
// Create an image destination.
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL((__bridge CFURLRef)outputURL, kUTTypeJPEG , 1, NULL);
if (imageDestination == NULL ) {
// Handle failure.
NSLog(@"Error -> failed to create image destination.");
return;
}
// Add your image to the destination.
CGImageDestinationAddImage(imageDestination, capturedImage.CGImage, (__bridge CFDictionaryRef)mutableMetadata);
// Finalize the destination.
if (CGImageDestinationFinalize(imageDestination) == NO) {
// Handle failure.
NSLog(@"Error -> failed to finalize the image.");
}
CFRelease(imageDestination);
根据我的测试,执行时间与执行时间大致相同或更快:
NSData *data = UIImageJPEGRepresentation(capturedImage, 1.0);
[data writeToURL:outputURL atomically:YES];
...您可以保留 EXIF 数据!
如果你想确保你的 UI 保持响应,你也可以将它分派到后台队列:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Do the image saving here...
});
重要提示:您需要将ImageIO.framework 和MobileCoreServices.framework 添加到目标的构建阶段,并将它们导入您执行图像保存的类中:
#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>
其他说明
据我了解,在这种情况下,按照示例中的建议保存图像时,我们不会造成生成损失。我们正在使用 UIImage 的 CGImage 属性,正如文档所述:
底层 Quartz 图像数据