如何将 'UIImagePickerController.InfoKey.originalImage' 转换为 'UIImage'

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

我正在开发 iOS phone 应用程序,我想拍照并将其存储在应用程序中。

我可以使用 UIImagePickerController 拍照,但我无法将它存储在我的数据库中。我在这个应用程序中使用 CoreData 存储数据但是对于图片,似乎将图片存储在文件夹中并将文件路径存储在 Coredata 中更容易。问题是我可以获取用相机拍摄的照片,但无法获取 PNG 数据以将其存储在我的文件夹中。

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

问题出在我尝试获取 png 数据时。我需要一个 UIImage 才能使用 .pngData(),但是当我尝试将我的图片对象从 UIImagePickerController.InfoKey.originalKey 转换为 UIImage 时,我收到以下警告消息:

"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" )

我也曾尝试让我的图片对象作为 UIImagePickerController.InfoKey 对象而不将其转换为 UIImage 对象,但在这种情况下我有以下错误消息:

"Value of type 'UIImagePickerController.InfoKey' has no member 'pngData' " and the method UIImagePNGRepresentation() is not working because the expected argument type is also 'UIImage'

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

你应该使用 UIImagePickerControllerDelegate,像这样

extension ViewController: UIImagePickerControllerDelegate {

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

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

}

你看,来自 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)
}

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

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

}

正如@Scriptabel 所说,

您需要在函数中使用此委托和 access/save 您的图像。

Class VC: UIViewController, UIImagePickerControllerDelegate { 

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


let picture = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let data = picture.pngData()        

    //Store the picture in an app folder
    let fileManager = FileManager.default
    let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image")


    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()

 }
}