我尝试使用此示例代码访问Exif数据:
let fileextension = NSURL(fileURLWithPath: mDir + "/" + f).pathExtension
if fileextension == "PSD" || fileextension == "NEF" || fileextension == "3FR" || fileextension == "CR2" || fileextension == "DNG" || fileextension == "JPEG" || fileextension == "JPG" || fileextension == "PSB" || fileextension == "RAF" || fileextension == "TIF" {
let fileattr = try fileManager.attributesOfItem(atPath: mDir + "/" + f)
let filesize = fileattr[FileAttributeKey.size] as! Int64
let UrlPath = URL(fileURLWithPath: mDir + "/" + f)
let imageSource = CGImageSourceCreateWithURL(UrlPath as CFURL, nil)
let result = CGImageSourceCopyMetadataAtIndex(imageSource!, 0, nil)
let d = result as! [AnyHashable:Any]
let tiffDict = d["{TIFF}"] as! [AnyHashable:Any]
let filedate = tiffDict["DateTime"] as! Date
我有这个错误:
无法将类型'__NSCFType'(0x7fff89750188)的值强制转换为'NSDictionary'(0x7fff89750fe8)。
但是此示例代码在操场上工作。
任何解释吗?
[我使用CGImageMetadataCopyTags
提取元数据作为数组,然后使用CGImageMetadataTagCopyName
和CGImageMetadataTagCopyValue
将数据映射到快速字典中
let extensions = ["PSD", "NEF", "3FR", "CR2", "DNG", "JPEG", "JPG", "PSB", "RAF", "TIF"]
let fileManager = FileManager.default
let url = URL(fileURLWithPath: mDir + "/" + f)
var metaData = [String: Any]()
if extensions.contains(url.pathExtension) {
let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil)
if let result = CGImageSourceCopyMetadataAtIndex(imageSource!, 0, nil) {
if let array = CGImageMetadataCopyTags(result) as? [CGImageMetadataTag] {
metaData = array.reduce(into: [String: Any]()) {
guard let name = CGImageMetadataTagCopyName($1),
let value = CGImageMetadataTagCopyValue($1)
else {
return
}
$0[String(name)] = value
}
}
}
}
[注意,这仅给出了像“ ShutterSpeedValue”这样的标签名称,以包括“ exif”,“ tiff”,“ xmp”这样的标签类型,我们也可以得到前缀:
guard let prefix = CGImageMetadataTagCopyPrefix($1),
let name = CGImageMetadataTagCopyName($1),
let value = CGImageMetadataTagCopyValue($1)
else { return }
$0["\(prefix):\(name)"] = value