How can I save a photo taken with UIImagePickerCon

2019-08-12 08:38发布

问题:

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?

I have heard NSUserDefaults would be a mistake. All I need to save is a single image, never more.

回答1:

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

Hope this helps you