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

时间:2019-07-29 10:34:27

标签: swift uiimage uiimagepickercontroller

我正在开发一个iOS手机应用程序,我想拍照并将其存储在该应用程序中。

我可以使用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时,我收到以下警告消息:

  

“从'UIImagePickerController.InfoKey'到无关类型'UIImage'的广播始终失败”。   另外,我不明白为什么需要转换它,因为我在AppleDevelopper网站上发现:“此键的值是UIImage对象。” (键为“ static let originalImage:UIImagePickerController.InfoKey”)

我也尝试过将图片对象作为UIImagePickerController.InfoKey对象,而不将其转换为UIImage对象,但是在这种情况下,我会收到以下错误消息:

  

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

2 个答案:

答案 0 :(得分:2)

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

}

答案 1 :(得分:1)

如@Scriptabel所述,

您将需要使用此委托并在函数中访问/保存图像。

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

 }
}