【问题标题】:How to save image to internal memory of app after taking it by camera相机拍摄后如何将图像保存到应用程序的内部存储器
【发布时间】:2018-02-14 17:35:21
【问题描述】:

我正在开发一个应用程序,在该应用程序中我提示用户用他的手机拍照,然后我把这张照片放到我的imageView但我想保存这张照片,以便在用户重新启动应用程序后拥有它。

这是我的代码:

var imagePicker: UIImagePickerController!
    //MARK: - Take image
    @IBAction func takePhoto(_ sender: UIButton) {

        imagePicker =  UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        present(imagePicker, animated: true, completion: nil)
    }


    //MARK: - Done image capture here
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        imagePicker.dismiss(animated: true, completion: nil)
        imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

    }

使用上面的代码,我拍照并将其放入我的imageView,但我不知道如何将其保存在例如UserDefaults

【问题讨论】:

    标签: ios swift swift3 uiimageview


    【解决方案1】:

    使用此代码 -

    保存图片 -

    UserDefaults.standard.set(UIImagePNGRepresentation(image), forKey: "image")
    

    检索图像 -

    let imageData: Data? = UserDefaults.standard.object(forKey: "image") as? Data
    if let imageData = imageData
    {
       var image = UIImage(data: imageData)
    }
    

    【讨论】:

    • 您好,感谢您的回答,我对其进行了测试并检索了我使用的图像:UserDefaults.standard.value(forKey: "image1") as? UIImage ?? UIImage() 但什么也没发生
    • 当我尝试第一次启动应用程序时,由于imageData! 而崩溃,您应该使用可选的imageData ?? Data() to avoid crashes! 进行更改
    • 编辑了答案,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多