【问题标题】:How to save image after selecting from UIImagepickercontroller从 UIImagepickercontroller 选择后如何保存图像
【发布时间】:2015-07-20 09:52:54
【问题描述】:

我正在使用 Swift 和 Xcode 6 构建一个 iOS 应用程序。我已经实现了从 UIImagePickerController 中选择图像并设置到 UIImageView 中的功能。

这是我从 UIImagePickerController 中选择图像的代码:

@IBAction func loadImageButtonTapped(sender: UIButton) {
        imagePicker.allowsEditing = false
        imagePicker.sourceType = .PhotoLibrary
        // imagePicker.sourceType = .Camera
        //imagePicker.sourceType = .SavedPhotosAlbum

        presentViewController(imagePicker, animated: true, completion: nil)
    }


    // MARK: - UIImagePickerControllerDelegate Methods
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
           // imageView.contentMode = .ScaleAspectFit
            imageView.image = pickedImage

        }

        dismissViewControllerAnimated(true, completion: nil)
    }

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true, completion: nil)
    }

现在我正在寻找存储此图像的最佳方式,当用户再次进入应用程序时,我可以获取图像并显示在 uiimageview 中。

可以帮助我如何实现这一点。

感谢您的帮助!

提前致谢!

【问题讨论】:

    标签: ios swift uiimageview uiimage uiimagepickercontroller


    【解决方案1】:

    试试这个。

    let imageData: NSData = UIImageJPEGRepresentation(yourImage, 0.9)
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let destinationPath = documentsPath.stringByAppendingPathComponent("filename.jpg")
    imageData.writeToFile(destinationPath, atomically: false)
    

    然后再检索图像:

    let loadedImage = UIImage(contentsOfFile: destinationPath)
    

    【讨论】:

    • 能否请您解释一下当我必须在 viewDidLoad.let 中获取 uiimage 时,destinationPath 是什么?loadedImage = UIImage(contentsOfFile:destinationPath)
    • 您可以像保存图像时一样执行相同的操作来获取目标路径。即let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String... etc
    • 这是最简单的方法。如果你想要更全面的方式,你应该考虑 Core Data。这需要更多设置。
    • 你知道一些关于Core Data保存图像的教程吗?
    • 如果您只想保存图像,我不会使用核心数据。我会坚持使用文件管理器。如上所示,您对使用文件管理器有什么顾虑?
    猜你喜欢
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多