如何保存用UIImagePickerController相机拍摄的照片以稍后在应用程序中显示? [英] How can I save a photo taken with UIImagePickerController camera to be displayed later in the app?
问题描述
我正在让用户使用UIImagePickerController拍摄照片,我需要将其保存到应用程序中,以便在以后需要查看时可以显示它。我该怎么做?
I am having the user take a photo with UIImagePickerController and I need it to be saved to the app so that it can be displayed when they need to see it later. How can I accomplish this?
我听说NSUserDefaults是一个错误。我需要保存的只是一个图像,再也没有。
I have heard NSUserDefaults would be a mistake. All I need to save is a single image, never more.
推荐答案
这里是将图像保存到文档文件夹的功能
Here is the function to save your image to document folder
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
}
这里是获取函数具有图像名称的文档目录路径
Here is the function to get your document directory path with image name
func fileInDocumentsDirectory(filename: String) -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
return documentsFolderPath.stringByAppendingPathComponent(filename)
}
这里是一个示例如何使用图像路径
Here is an example of how to use your image path
let imagePath = fileInDocumentsDirectory(myImageName)
这是将图片保存到该文件夹的方式
And here is how you save your image to that folder
saveImage(image, path: imagePath)
现在最后一部分是获取图像,因此使用此功能获取图像
Now the last part is to get your image, so use this function to get your image
func loadImageFromPath(path: String) -> UIImage? {
let image = UIImage(contentsOfFile: path)
if image == nil {
println("Image not available at: (path)")
}
return image
}
这是使用上述功能的方式
And here is how you use the above function
image = loadImageFromPath(imagePath)
imageView.image = image
希望这对您有帮助
这篇关于如何保存用UIImagePickerController相机拍摄的照片以稍后在应用程序中显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!