How to convert 'UIImagePickerController.InfoKey.originalImage' into 'UIImage'

Man*_*lli -1 uiimagepickercontroller uiimage swift

I'm developping an iOS phone app and I want to take a picture and store it in the app.

I am able to take the picture using a UIImagePickerController but I can't store it in my database. I'm using CoreData to store data in this app but for the picture, it seems that it is easier to store the picture in a folder and store the file path in Coredata. The issue is that I can get the picture i've took with the camera but I can't get the PNG data to store it in my folder.

func takePhoto(){
        //Take the picture with the camera
        imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        if !UIImagePickerController.isSourceTypeAvailable(.camera){
            let alertController = UIAlertController.init(title: nil, message: "Camera is not available", preferredStyle: .alert)
            let okAction = UIAlertAction.init(title: "Alright", style: .default, handler: {(alert: UIAlertAction!) in })
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }
        else{ imagePickerController.sourceType = .camera }

        present(imagePickerController, animated: true, completion: nil)

        //Store the picture in an app folder
        let fileManager = FileManager.default
        let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image")
        let picture = UIImagePickerController.InfoKey.originalImage as? UIImage
        let data = picture?.pngData()
        fileManager.createFile(atPath: imagePath as String, contents: data, attributes: nil)

        //Store the file path in CoreData
        let image = Image(context: self.persistenceManager.context)
        image.pathName = imagePath
        self.persistenceManager.saveContext()
}
Run Code Online (Sandbox Code Playgroud)

The problem is when I try to get the png data. I need a UIImage to use .pngData() but when I try to convert my picture object into UIImage from UIImagePickerController.InfoKey.originalKey I have the following warning message:

"Cast from 'UIImagePickerController.InfoKey' to unrelated type 'UIImage' always fails". Also, I don't understand why I need to convert it because I found in the AppleDevelopper website that: "The value for this key is a UIImage object." (the key is "static let originalImage: UIImagePickerController.InfoKey" )

I've also tried to let my picture object as an UIImagePickerController.InfoKey object without converting it into an UIImage object but in this case I have the following error message:

“类型的值'UIImagePickerController.InfoKey'没有成员 'pngData'”并且方法 UIImagePNGRepresentation() 不起作用,因为预期的参数类型也是 'UIImage'

Scr*_*ble 5

UIImagePickerController.InfoKey.originalImage 是一个字符串...它是一个键,而不是实际的图像。

你应该使用UIImagePickerControllerDelegate,像这样

extension ViewController: UIImagePickerControllerDelegate {

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

        let image = info[.originalImage] as? UIImage
    }

}
Run Code Online (Sandbox Code Playgroud)

您会看到,来自 UIPickerController 的信息作为类型为 的字典传递[UIImagePickerController.InfoKey : Any]UIImagePicker.InfoKey包含此字典中使用的所有键,因此您可以使用它们来访问值。

编辑:

所以你的 takePhoto 函数只需要显示选择器,然后在委托方法中处理响应:

func takePhoto(){
    //Take the picture with the camera
    imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self
    if !UIImagePickerController.isSourceTypeAvailable(.camera){
        let alertController = UIAlertController.init(title: nil, message: "Camera is not available", preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: "Alright", style: .default, handler: {(alert: UIAlertAction!) in })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    else{ imagePickerController.sourceType = .camera }

    present(imagePickerController, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

然后在您的委托中,您可以使用选定的图像

extension ViewController: UIImagePickerControllerDelegate {

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

       let fileManager = FileManager.default
       let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image")
       let picture = info[.originalImage] as? UIImage
       let data = picture?.pngData()
       fileManager.createFile(atPath: imagePath as String, contents: data, attributes: nil)

       //Store the file path in CoreData
       let image = Image(context: self.persistenceManager.context)
       image.pathName = imagePath
       self.persistenceManager.saveContext()
    }

}
Run Code Online (Sandbox Code Playgroud)