通过编辑 EXIF 数据保存(覆盖)我的 jpg 文件

Save (override) my jpg file with editing EXIF data

我正在打开并编辑我的 jpg 文件中的 EXIF(或 TIFF...)数据。 请帮我用编辑数据保存(覆盖)我的 jpg 文件。 使用这个简单的代码:

let fileURL = URL(fileURLWithPath: "/Users/test/Pictures/IMG_2808.jpg")

if let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil) {
    var imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
    let exifDict = imageProperties?[kCGImagePropertyExifDictionary]

    if let UserComment = exifDict?[kCGImagePropertyExifUserComment] ?? nil {
        print("kCGImagePropertyExifUserComment: \(UserComment)")
    }
    else {
        exifDict!.setValue("My comment...", forKey: kCGImagePropertyExifUserComment as String)
        imageProperties![kCGImagePropertyExifDictionary] = exifDict
        
//      What I should do in the next step for update and override my jpg file on disk?
//      Maybe this is not nice way for this realisation? Please help
//
    }
}

经过一些测试我找到了解决方案:

let fileURL = URL(fileURLWithPath: "/Users/test/Pictures/IMG_2808.jpg")

if let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil) {
    var imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
    let exifDict = imageProperties?[kCGImagePropertyExifDictionary]

    if let UserComment = exifDict?[kCGImagePropertyExifUserComment] ?? nil {
        print("kCGImagePropertyExifUserComment: \(UserComment)")
    }
    else {
        exifDict!.setValue("My comment...", forKey: kCGImagePropertyExifUserComment as String)
        imageProperties![kCGImagePropertyExifDictionary] = exifDict
     
        if let imageDestination = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeJPEG, 1, nil) {

            CGImageDestinationAddImageFromSource(imageDestination, imageSource, 0, imageProperties as CFDictionary?)

            CGImageDestinationFinalize(imageDestination)
        }
    }
}

我不知道这个解决方案是否正确,但它确实有效! 有更完善的方法欢迎评论