[英]How to save UIImage from UIImagePicker in Documents folder and get string for path to save in Core Data in Swift
I'm building my first Swift application. 我正在构建我的第一个Swift应用程序。 In it, the user needs to be able to choose an image from the iPhone's photo library.
在其中,用户需要能够从iPhone的照片库中选择图像。 Then I want to save this image to keep permanently for use in other parts of the app.
然后我想保存此图像以永久保留在应用程序的其他部分。
I know it is possible to convert a UIImage
to NSData
and save as binary data in Core Data, but I have read that it is a bad idea to store Binary Large Objects, such as images directly in Core Data. 我知道可以将
UIImage
转换为NSData
并将其保存为Core Data中的二进制数据,但我已经读过,将二进制大对象(例如图像)直接存储在Core Data中是个坏主意。
I have seen it suggested that you should save the image file in the Documents folder and then just save a string for the file path in Core Data. 我已经看到它建议你应该将图像文件保存在Documents文件夹中,然后只保存Core Data中文件路径的字符串。 But I haven't seen an actual example of the code snippet needed to do this.
但我还没有看到执行此操作所需的代码片段的实际示例。
Steps to accomplish: 完成的步骤:
UIImage
from image picker. UIImage
。 (this part I've got working) Here is the code for the UIImagePicker
that I'm starting with: 这是我开始使用的
UIImagePicker
的代码:
@IBAction func openImagePicker(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!)
{
self.dismissViewControllerAnimated(true, completion: nil)
myImageView.image = image
}
So the UIImage
displayed in myImageView
.image is what I need to do something with. 所以
myImageView
.image中显示的UIImage
就是我需要做的事情。
You can save your image with following code 您可以使用以下代码保存图像
let imageData = NSData(data:UIImagePNGRepresentation(wineImage.image))
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docs: String = paths[0] as! String
let fullPath = docs.stringByAppendingPathComponent("yourNameImg.png")
let result = imageData.writeToFile(responseData, atomically: true)
Inside fullPath you'll find the complete path, the image will be stored in app's document dir. 在fullPath内部,您将找到完整的路径,图像将存储在应用程序的文档目录中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.