簡體   English   中英

如何使用 Swift 通過 PHAsset 訪問 UIImage 的元數據

[英]How to get access to metadata for UIImage via PHAsset using Swift

我正在嘗試獲取此工作代碼,該代碼通過 ImagePicker 中的 selectedImage 檢索 UIImage 並通過 savePhoto 方法保存它,以獲取 UImage 的元數據:

原始代碼:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){

    if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {

    //Successfully got the image, now upload it

        //Get a reference to the camera view controller and call the savePhoto method
        let cameraVC = self.selectedViewController as? CameraViewController

        if let cameraVC = cameraVC {
            cameraVC.savePhoto(image: selectedImage)
        }

//Dismiss the picker
picker.dismiss(animated: true, completion: nil)
}
}

這是我嘗試過的,但是 thisAsset 總是返回 nil 所以它基本上跳過了整個方法。

我試過的代碼:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){

var arrImageIdentifiers = String()


    if let thisAsset:PHAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
          arrImageIdentifiers.append(thisAsset.localIdentifier)

        //Get a reference to the camera view controller and call the savePhoto method
        let cameraVC = self.selectedViewController as? CameraViewController

        let manager = PHImageManager.default()

        manager.requestImage(for: thisAsset, targetSize: CGSize(width: 300.0, height: 300.0), contentMode: .aspectFit, options: nil, resultHandler: {(thisImage, _) in




        if let cameraVC = cameraVC {
            cameraVC.savePhoto(image: thisImage!)
        }
            })
        }
    self.dismiss(animated: true, completion: nil)
  }}

從上面的原始代碼中獲取照片元數據(創建日期、位置等)的最簡單方法是什么?

extension PHAsset {
func metadata(_ completion: @escaping (Metadata?) -> Void) {
    let options = PHContentEditingInputRequestOptions()
    options.isNetworkAccessAllowed = true

    requestContentEditingInput(with: options) { input, _ in
        guard let url =  input?.fullSizeImageURL,
            let image = CIImage(contentsOf: url) else {
            completion(nil)
            return
        }
        let properties = image.properties
        let tiffDict = properties["{TIFF}"] as? [String: Any]
        let make = tiffDict?["Make"] as? String ?? ""
        completion(make)
    }
}


asset.metadata { metadata in
    guard let metadata = metadata else {
       return
    }
    // You can explore all available metadata values here. 
}

您從第一個代碼中獲得的圖像不包括元數據。 您的第二個代碼更接近正確; 您需要將 go 返回 PHAsset 並從照片庫中獲取元數據。

這是我嘗試過的,但是thisAsset總是返回 nil

因為您忘記獲取照片庫的用戶授權 否則,您將無法訪問 PHAsset。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM