2013-10-30 56 views
5

我正在创建照片编辑应用程序,到目前为止,我已成功读取图像文件中的元数据(获得此问题的答案:Reading Camera data from EXIF while opening NSImage on OS X)。在OS X中将图像元数据(EXIF/TIFF/IPTC)写入图像文件

source = CGImageSourceCreateWithURL((__bridge CFURLRef)url, NULL); 
NSDictionary *props = (__bridge_transfer NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL); 

这将图像文件的所有元数据复制到字典,它工作得很好。但是,我无法找到如何将这些元数据写回新创建的NSImage(或图像文件)。这是我如何保存我的文件(其中img是NSImage中实例没有元数据和self.cachedMetadata从初始图像读取字典):

NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[img TIFFRepresentation]]; 
[rep setProperty:NSImageEXIFData withValue:self.cachedMetadata]; 
NSData *data; 
if([[fileName lowercaseString] rangeOfString:@".png"].location != NSNotFound){ 
    data = [rep representationUsingType:NSPNGFileType properties:nil]; 
}else if([[fileName lowercaseString] rangeOfString:@".tif"].location != NSNotFound){ 
    data = [rep representationUsingType:NSTIFFFileType properties:nil]; 
}else{ //assume jpeg 
    data = [rep representationUsingType:NSJPEGFileType properties:@{NSImageCompressionFactor: [NSNumber numberWithFloat:1], NSImageEXIFData: self.cachedMetadata}]; 
} 

[data writeToFile:fileName atomically:YES]; 

我怎么能写的元数据?我以前只是为JPEG写了EXIF(字典以前只是EXIF),但是因为EXIF缺少一些初始图像(IPTC和TIFF标签)的字段,所以我需要更改我的阅读方法。现在我拥有所有的数据,但我不知道如何将它写入新创建的图像文件。

谢谢, 可以。

+0

你好!我或多或少处于相同的情况,但无法理解您的解决方案。我有关键字,标题和说明,我必须写信给IPTC部分的我知道路径。如何才能做到这一点?你可以看看这个问题,也许发表一个答案? http://stackoverflow.com/questions/23874865/write-iptc-data-to-file – user2452250

回答

4

发现从另一个StackOverflow的问题的答案:How do you overwrite image metadata?

(从问题本身采取和修改我的需要的代码,其中包含了回答我的问题)

//assuming I've already loaded the image source and read the meta 
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef) data, NULL); 
CFStringRef imageType = CGImageSourceGetType(source); 

//new empty data to write the final image data to 
NSMutableData *resultData = [NSMutableData data]; 
CGImageDestinationRef imgDest = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)(resultData), imageType, 1, NULL); 

//copy image data 
CGImageDestinationAddImageFromSource(imgDest, source, 0, (__bridge CFDictionaryRef)(window.cachedMetadata)); 
BOOL success = CGImageDestinationFinalize(imgDest); 

这完美地工作了回写所有元数据,包括EXIF,TIFF和IPTC。

+0

这是否也保留剪切路径(如果存在)? – sharkyenergy

+0

@sharkyenergy说实话我还没有尝试过。 –

+0

我在这里打开了一个新的问题:http://stackoverflow.com/questions/32160528/read-non-standard-properties-from-an-image-in-objective-c将在今晚晚些时候添加赏金。如果你有自己的照片编辑软件,可能对你也很有趣。 – sharkyenergy

0

您可以尝试使用或查看“exiv2”工具中的代码。

+0

我有一个商业项目和商业许可证要求联系创作者。我最好坚持使用内置的解决方案。有一种方法可以完全提取所有数据,还必须有方法将所有数据写回图像。 –