2013-10-30 54 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

我有一個商業項目和商業許可證要求聯繫創作者。我最好堅持使用內置的解決方案。有一種方法可以完全提取所有數據,還必須有方法將所有數據寫回圖像。 –