我搜索了从图片文件中获取 EXIF 数据并将其写回 Swift 的方法。但我只能找到不同语言的预定义库。
我还找到了对“CFDictionaryGetValue”的引用,但是我需要哪些键来获取数据?我该如何写回它?
我用它来获取图像文件中的EXIF信息:
import ImageIO
let fileURL = theURLToTheImageFile
if let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil) {
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)
if let dict = imageProperties as? [String: Any] {
print(dict)
}
}
它为您提供了一本包含各种信息(例如颜色配置文件)的字典 - EXIF 信息具体位于
dict["{Exif}"]
。
斯威夫特4
extension UIImage {
func getExifData() -> CFDictionary? {
var exifData: CFDictionary? = nil
if let data = self.jpegData(compressionQuality: 1.0) {
data.withUnsafeBytes {(bytes: UnsafePointer<UInt8>)->Void in
if let cfData = CFDataCreate(kCFAllocatorDefault, bytes, data.count) {
let source = CGImageSourceCreateWithData(cfData, nil)
exifData = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil)
}
}
}
return exifData
}
}
斯威夫特5
extension UIImage {
func getExifData() -> CFDictionary? {
var exifData: CFDictionary? = nil
if let data = self.jpegData(compressionQuality: 1.0) {
data.withUnsafeBytes {
let bytes = $0.baseAddress?.assumingMemoryBound(to: UInt8.self)
if let cfData = CFDataCreate(kCFAllocatorDefault, bytes, data.count),
let source = CGImageSourceCreateWithData(cfData, nil) {
exifData = CGImageSourceCopyPropertiesAtIndex(source, 0, nil)
}
}
}
return exifData
}
}
您可以使用 AVAssetExportSession 写入元数据。
let asset = AVAsset(url: existingUrl)
let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
exportSession?.outputURL = newURL
exportSession?.metadata = [
// whatever [AVMetadataItem] you want to write
]
exportSession?.exportAsynchronously {
// respond to file writing completion
}
我使用这种方法:
extension Data { // for UIImage.data only
var metadata: [AnyHashable : Any]? {
let options = [kCGImageDestinationLossyCompressionQuality : NSNumber(value: 1),
kCGImagePropertyHasAlpha : kCFBooleanTrue,
kCGImageSourceShouldCache : kCFBooleanFalse] as CFDictionary
guard let source = CGImageSourceCreateWithData(self as CFData, options) else { return nil }
return CGImageSourceCopyPropertiesAtIndex(source, 0, options) as? [AnyHashable: Any]
}
}
任何
image
都可以将其用作
guard let data = image.jpegData(compressionQuality: 1),
var metadata = data.metadata
else {
return nil
}
EXIF -> metadata[kCGImagePropertyExifDictionary] as? [AnyHashable : Any]
TIFF -> metadata[kCGImagePropertyTIFFDictionary] as? [AnyHashable : Any]
GPS -> metadata[kCGImagePropertyGPSDictionary] as? [AnyHashable : Any]
& etc.
用这个多变的字典做任何你想做的事。