EXIF数据读写



我搜索从图片文件中获取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}"]中。

Swift 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
}

最新更新