我尝试从图片中检索 exif 数据。 我可以将其加载到字典中,但无法使用该字典。
我当前的代码是:
import Cocoa
import ImageIO
let path = "/Volumes/Olivier/Original/Paysage/affoux/_OPI7684.NEF"
let UrlPath = URL(fileURLWithPath: path)
UrlPath.isFileURL
UrlPath.pathExtension
UrlPath.hasDirectoryPath
let imageSource = CGImageSourceCreateWithURL(UrlPath as CFURL, nil)
let imageProp = CGImageSourceCopyPropertiesAtIndex(imageSource!, 0, nil)
var key = "kCGImagePropertyWidth" as NSString
let h :NSDictionary = CFDictionaryGetValue(imageProp, kCGImagePropertyWidth)
最后一行根本不起作用。 有什么解决办法吗? 谢谢
最佳答案
问题是您的 key 名称错误。您的意思是kCGImagePropertyPixelWidth
。而且它不是一个字符串。这是一个常数。所以它不应该用引号引起来;直接使用常量即可,不用担心它的值是多少。
我还建议您在此过程的早期转换为 Swift 字典。这是实际的工作代码,您可以根据它自己进行建模:
let src = CGImageSourceCreateWithURL(url as CFURL, nil)!
let result = CGImageSourceCopyPropertiesAtIndex(src, 0, nil)!
let d = result as! [AnyHashable:Any]
let width = d[kCGImagePropertyPixelWidth] as! CGFloat
let height = d[kCGImagePropertyPixelHeight] as! CGFloat
当然,这段代码非常糟糕,因为每一行都包含一个感叹号(这意味着“让我崩溃”),但在现实生活中我不会崩溃,所以我允许它继续存在。
关于swift - 使用 swift 4 检索 NSDictionary 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50514035/