如何保存从Swift中的UIImagePickerController中拾取的图像?

时间:2016-02-28 17:18:37

标签: ios swift uiimagepickercontroller

我正在构建一个应用程序,我让用户从其照片库中选择一个图像。我正在使用此代码来保存它。

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    imgPicker.dismissViewControllerAnimated(true, completion: nil)
    NSUserDefaults.standardUserDefaults().setValue(image, forKey: "bgImage")
}

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

我后来发现你无法使用NSUserDefaults保存图像,但是你可以保存拾取图像的路径,保存并加载“if let ...”

但我不知道该怎么做(找到路径并保存)。这个想法是让用户选择视图背景图像,有点像Whatsapp的作用。

如果我错了并且您无法存储路径,是否有任何简单的方法可以在不使用在线服务器的情况下保存所选图像?

2 个答案:

答案 0 :(得分:10)

您可以使用NSUserDefaults保存和检索它:

//Save image
let img = UIImage() //Change to be from UIPicker
let data = UIImagePNGRepresentation(img)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "myImageKey")
NSUserDefaults.standardUserDefaults().synchronize()

//Get image
if let imgData = NSUserDefaults.standardUserDefaults().objectForKey("myImageKey") as? NSData {
    let retrievedImg = UIImage(data: imgData)
}

如果您愿意,也可以读取/写入文件:

//Save image
let img = UIImage() //Change to be from UIPicker
let data = UIImagePNGRepresentation(img)!
do {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    try data.writeToFile("\(documentsPath)myImage", options: [])

} catch {
    print("Error")
}

//Get image
do {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let readData = try NSData(contentsOfFile: "\(documentsPath)myImage", options: [])
    let retreivedImage = UIImage(data: readData)
}
catch {
    print("Error")
}

Swift 3

//Save image
let data = UIImagePNGRepresentation(pickedImage)!
do {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    try data.write(to: URL(string: "\(documentsPath)/myImage")!, options: .atomic)
} catch {
    print("Error")
}

//Get image
do {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let readData = try Data(contentsOf: URL(string: "\(documentsPath)/myImage")!)
    let retreivedImage = UIImage(data: readData)
} catch {
    print("Error")
}

答案 1 :(得分:-1)

有两种方法,一种是你要描述的,但是非常混乱,我建议你采用图像,转换成图像数据并将其存储在本地应用程序中,就像在sqlite数据库中或在用户默认的数组。但是,在用户默认值中保存那么多数据并不是一个好习惯。所以,我会把它存储在本地,我不会用凌乱的sqlite代码来做,而是用核心数据来做。

class AddImageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet var popUpThePickerButton: UIButton! //click on this button to appear the imagePicker
    @IBOutlet var addPictureButton: UIButton! //when this button clicked saveImage method is called and there you save the imageData wherever you want

    let picker = UIImagePickerController()
    var selectedImage : UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
        picker.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // when popUpThePickerButton is clicked
    @IBAction func selectPictureFromPhotos(sender: UIButton) { 
        picker.editing = false
        picker.sourceType = .PhotoLibrary

        presentViewController(picker, animated: true, completion: nil)
    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        self.selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage 
        dismissViewControllerAnimated(true, completion: nil)
    }

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

// then save this image data in your database and when you want to show that image you can just turn the image data to image again

    @IBAction func saveImage(sender: UIButton) {
        let imageData = UIImagePNGRepresentation(self.selectedImage)
        //save this image data in database
    }
}