Get image name UIImagePickerController in Swift(在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Swift 中获取图像名称 UIImagePickerController


基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01