如何将元数据永久保存到UIImage?

时间:2019-02-04 17:31:36

标签: ios swift xcode exif

我想将UIImage和元数据保存到我的照片库中。我已经能够保存它,但是我的元数据也不会保存。有什么帮助吗? (顺便说一句,我正在使用http://exif.regex.info/exif.cgi读取元数据)我的代码:

保存:

@IBAction func save(_ sender: AnyObject) {
    UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}

//MARK: - Add image to Library
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }
}

添加元数据:

    let image = info[UIImagePickerControllerOriginalImage] as! UIImage

    let jpeg = UIImageJPEGRepresentation(image, 1.0)
    var source: CGImageSource? = nil
    source = CGImageSourceCreateWithData((jpeg as CFData?)!, nil)
    let metadata = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil) as? [AnyHashable: Any]
    var metadataAsMutable = metadata
    var EXIFDictionary = (metadataAsMutable?[(kCGImagePropertyExifDictionary as String)]) as? [AnyHashable: Any]
    var GPSDictionary = (metadataAsMutable?[(kCGImagePropertyGPSDictionary as String)]) as? [AnyHashable: Any]

    if !(EXIFDictionary != nil) {
        EXIFDictionary = [AnyHashable: Any]()
    }
    if !(GPSDictionary != nil) {
        GPSDictionary = [AnyHashable: Any]()
    }

    GPSDictionary![(kCGImagePropertyGPSLatitude as String)] = 3.14
    GPSDictionary![(kCGImagePropertyGPSLongitude as String)] = 3.14

    let UTI: CFString = CGImageSourceGetType(source!)!
    let dest_data = NSMutableData()
    let destination: CGImageDestination = CGImageDestinationCreateWithData(dest_data as CFMutableData, UTI, 1, nil)!
    CGImageDestinationAddImageFromSource(destination, source!, 0, (metadataAsMutable as CFDictionary?))
    CGImageDestinationFinalize(destination)

1 个答案:

答案 0 :(得分:0)

您可能正在获取元数据并将其附加到dest_data(无法从此处判断是否成功完成此操作),但是问题在于您没有将dest_data保存到照片中图书馆。您需要放弃使用过时的UIImageWriteToSavedPhotosAlbum,而要使用照片库:为资产创建PHAssetCreationRequest并调用addResource(with:data:options)