在 Swift 中获取图像名称 UIImagePickerController [英] Get image name UIImagePickerController in Swift

查看:9
本文介绍了在 Swift 中获取图像名称 UIImagePickerController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 UIImagePickerController 从手机库 (iOS) 中获取图像.在编辑模式之后,我将图像放到我的 UIImageView 中.我想将此图像保存在 Core Data 中以在另一个视图控制器中使用它

I use UIImagePickerController to get image from phone library (iOS). After edit mode i put image to my UIImageView. I want to save this image in Core Data to use it in another View Controllers

我如何在 Swift 中做到这一点.如果不可能,我必须使用哪些选项来保存图像?

How can i do it in Swift. If it is not possible what options do i have to save image ?

推荐答案

另一个不错的选择是您可以将图像保存到应用程序的文档目录中,您可以从任何地方检索该图像,如下面的代码所示:

Another good option is you can save your Image into Document Directory of your app and you can retrieve that image from anywhere like shown in below code:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    self.dismissViewControllerAnimated(true, completion: nil)
    let tempImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    // save your image here into Document Directory
    saveImage(tempImage, path: fileInDocumentsDirectory("tempImage"))

}

这里是辅助函数:

func saveImage (image: UIImage, path: String ) -> Bool{

    let pngImageData = UIImagePNGRepresentation(image)
    //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
    let result = pngImageData.writeToFile(path, atomically: true)

    return result

}

// Get the documents Directory

func documentsDirectory() -> String {
    let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
    return documentsFolderPath
}
// Get path for a file in the directory

func fileInDocumentsDirectory(filename: String) -> String {
    return documentsDirectory().stringByAppendingPathComponent(filename)
}

这样您就可以从文档目录中检索该图像:

And this way you can retrieve that image from Document Directory:

@IBAction func setImage(sender: AnyObject) {

    imageV.image = loadImageFromPath(fileInDocumentsDirectory("tempImage"))
}

这里是辅助函数:

func loadImageFromPath(path: String) -> UIImage? {

    let image = UIImage(contentsOfFile: path)

    if image == nil {

        println("missing image at: (path)")
    }
    println("(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
    return image

}

希望对你有所帮助.

这篇关于在 Swift 中获取图像名称 UIImagePickerController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆