如果图像没有EXIF数据,我试图将EXIF数据设置为NSImage。其实我只想设置DateTimeOriginal。但我的方法不起作用。
let completePath = "/Users/stefocdp/image.jpg"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm:ss"
let folderAttributes: NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(completePath, error: nil)!
var dateString: String = dateFormatter.stringFromDate(folderAttributes.objectForKey(NSFileCreationDate) as! NSDate)
for obj in self.image.representations {
if let rep = obj as? NSBitmapImageRep {
if rep.valueForProperty(NSImageEXIFData) != nil {
//will be called if the image has exif data
// get exif dictonary
var exifData = rep.valueForProperty(NSImageEXIFData) as! NSDictionary
//convert CFString to String
var cfStr:CFString = kCGImagePropertyExifDateTimeOriginal
var nsTypeString = cfStr as NSString
var keySwiftString:String = nsTypeString as String
//get date from exif data
dateString = exifData.valueForKey(keySwiftString) as! String
//convert the date to NSDate
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy:MM:dd HH:mm:ss"
var date = dateFormatter.dateFromString(dateString)
//convert the NSDate back to String (only because I want another date format)
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm:ss"
dateString = dateFormatter.stringFromDate(date!)
} else {
//will be called if the image don't has exif data
//create dictionary for the exif data
var exifData = Dictionary<String, CFString>()
//convert the given date string to NSDate
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm:ss"
var date = dateFormatter.dateFromString(dateString)
//convert it back to String (different date format for exif data)
dateFormatter.dateFormat = "yyyy:MM:dd HH:mm:ss"
dateString = dateFormatter.stringFromDate(date!)
//convert CFString to String
var cfStr:CFString = kCGImagePropertyExifDateTimeOriginal
var nsTypeString = cfStr as NSString
var keySwiftString:String = nsTypeString as String
//add date to the exifData dictionary
exifData[keySwiftString] = dateString as CFString
//set the exifData to the NSBitmapImageRep
rep.setProperty(NSImageEXIFData, withValue: exifData)
//add the NSBitmapImageRep to the image
self.image.addRepresentation(rep)
}
}
else {
//is not an instance of NSBitmapImageRep
}
}
如果图像有exif数据,我只需从中获取DateTimeOriginal并将其存储在名为'dateString'的字符串变量中。但如果它没有exif数据(在'else'的情况下)我正在创建一个字典,我存储日期。然后我将exif数据添加到NSBitmapImageRep。最后我想将此imagerep添加到图像中。我想最后一步就是问题。
有人可以帮我解决我的问题吗?
谢谢!
答案 0 :(得分:0)
//您可以使用 CGImageSourceRef 而不是NSBitMapImageRef。对于初学者:
let url = NSURL(fileURLWithPath: imgfile) //imgfile = a String of the img file path
let cgiSrc = CGImageSourceCreateWithURL(url,nil)
let cfD:CFDictionaryRef = CGImageSourceCopyPropertiesAtIndex(cgiSrc!, 0, nil)!
let nsDic = NSDictionary(dictionary: cfD)
print(nsDic.description) //verify that it's working