How to save an image (path) within my app?

2019-01-29 07:46发布

问题:

I want to make an app, where the user fills out some kind of form, and attaches an image to it. The user picks a picture form the gallery (using UIImagePickerController). I already know how to display the image on the screen with info[UIImagePickerControllerOriginalImage] as? UIImage.

I want to make a file which will be used next time the app is opened, so the same image can be displayed with the notes. So preferably I want to save the path to the file so the next time I simply open it with UIImage(contentsOfFile: path). How can I get this path?

Some not so interesting code I have so far:

@IBAction func chooseFromGallery(sender: AnyObject) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
        imagePicker.allowsEditing = false
        self.presentViewController(imagePicker, animated: true, completion: nil)
    }
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    dismissViewControllerAnimated(true, completion: nil)

    self.image.image = info[UIImagePickerControllerOriginalImage] as? UIImage  // This works
    self.imagePath =  // What goes here?
    println(self.imagePath)
}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
}

Edit

After some reading I found out that there is no way of getting the path to an image which is saved outside the applications sandbox. So everybody looking for the same thing, stop, and use Bluehounds answer.
For more information about how files are handled in iOS (and OS X) read: https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

回答1:

A good place to store images is the documents directory. You can save to it and then retrieve images from it. I use these UIImage extensions for saving and retrieving images:

extension UIImage {
func save(fileName: String, type: String) {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

        if type.lowercaseString == "png" {
            let path = "\(documentsPath)/\(fileName).\(type)"
            UIImagePNGRepresentation(self).writeToFile(path, atomically: true)
        } else if type.lowercaseString == "jpg" {
            let path = "\(documentsPath)/\(fileName).\(type)"
            UIImageJPEGRepresentation(self, 1.0).writeToFile(path, atomically: true)
        } else {

        }
    }

convenience init?(fileName: String, type: String) {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        let path = "\(documentsPath)\(fileName).\(type)"
        self.init(contentsOfFile: path)
    }
}

Using this, I can store a file name rather than the entire path of an image using some data storing method such as Core Data.

Use:

someImage.save("SomeName" , type: "png")

if let image = UIImage(fileName: "SomeName", type: "png") {
}


回答2:

Here is How you can save your image

- (IBAction)saveImage {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *image = imageView.image; // imageView is where you are displaying image after selecting one from UIImagePicker
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];

}

You may fetch back this image like this

- (IBAction)getImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];

}

Update :

I believe that you title for question implies a bit differently. Coming back to your question, If you are planning to use only one image all the time, you can have a single image name and use it. This will override the earlier saved image at all times.

Else another option could be creating a simple plist or db and use the image along with timestamp to uniquely identify each image.

Swift Code to Save Image:

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
    if let dirPath = paths[0] as? String {
        let image = ***YOUR IMAGE***
        let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
        UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
    }
  }
}

To get the image can be very easliy relate from the same