EXIF数据读写

25

我搜索了如何从图片文件中获取EXIF数据并将其写回Swift。但我只找到了不同语言的预定义库。

我也发现了关于“CFDictionaryGetValue”的参考资料,但我需要哪些键来获取数据?以及如何将其写回?


1
已经有一个“swift”标签了,将其包含在问题标题中的意义是什么? - Léo Natan
2
好的,我想表明语言很重要。 我将不会在以后使用它。 - Peter Silie
当然,我会尽力而为。 :-) 我会看看我能做到什么程度。 - Peter Silie
3个回答

38

我正在使用这个工具获取图片文件的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} "]中。


1
我该如何将EXIF数据写回图像? - Genfood
这个回答没有提到“写”,有人知道吗? - Amos
1
请参考以下两个stackoverflow页面@Amos:https://dev59.com/HloT5IYBdhLWcg3w8jFm和https://dev59.com/QKHia4cB1Zd3GeqPW6qt,它们可以帮助你了解如何编写exif。 - Eric Aya
您还可以使用_kCGImagePropertyExifDictionary_作为键。 - Areal-17

11

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

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

2
对于Swift 5+,您想将data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>)->Void in ...更改为data.withUnsafeBytes { let bytes = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) ... } - Teo Sartori
该方法检索的 exif 数据比接受的数据少。 - Lubbo

1
你可以使用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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接