在Swift中获取图像名称UIImagePickerController [英] Get image name UIImagePickerController in Swift
问题描述
我使用UIImagePickerController从手机库(iOS)获取图像。编辑模式后,我把图像放到我的UIImageView。
我想在Core Data中保存此图像以在另一个View Controller中使用它
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
}
希望它会对你有所帮助。
Hope It will help you.
这篇关于在Swift中获取图像名称UIImagePickerController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!