如何使用swift拍摄照片并将其保存到本地应用程序中

时间:2016-06-22 22:14:34

标签: ios iphone swift camera

我正在处理一个应用程序,在当前阶段,当用户拍照时,图片将在应用程序中本地存储。

 @IBAction func CameraAction(sender: UIButton) {
let picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .Camera
    picker.allowsEditing = true
    self.presentViewController(picker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    picker.dismissViewControllerAnimated(true, completion: nil)

    //Save image
    let img = UIImage()
    let data = UIImagePNGRepresentation(img)
    NSUserDefaults.standardUserDefaults().setObject(data, forKey: "myImageKey")
    NSUserDefaults.standardUserDefaults().synchronize()
    NSLog("Image stored?")
    viewDidLoad()


}

据我所知,我的iPhone打开相机,我可以拍照。当我点击捕获并且"使用此图像"选项我不认为图片实际上是存储的,因为我还没有能够回忆起这些图片。

所以我在如何本地存储从UIImagePickerController中获取的图片,可能在文档文件夹中,如何调用它,以及如何没有NSUserDEfaults 的情况下寻求帮助。感谢。

3 个答案:

答案 0 :(得分:8)

这是您在NSUserDefaults中存储图像的方式:

  

正如我在评论中提到的,不建议这样做,如果用于多个图像,可能会导致严重的性能损失甚至崩溃。

let image = UIImage(named: "myImage")
let pngImage = UIImagePNGRepresentation(image) 

NSUserDefaults.standardUserDefaults().setObject(pngImage, forKey: "image")

并检索图像:

var retrievedImage = NSUserDefaults.standardUserDefaults().objectForKey("image") as! AnyObject

然后,显示图像:

imageView.image = UIImage(data: retrievedImage as! NSData)
  

这是如何将图像存储到文件中(更好):

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

}

你会这样称呼:

saveImage(image, path: imagePath)

然后,要检索图像,请使用此功能:

func loadImageFromPath(path: String) -> UIImage? {

    let image = UIImage(contentsOfFile: path)

    if image == nil {

        print("missing image at: \(path)")
    }
    print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
    return image

}

您可以这样称呼它:

image = loadImageFromPath(imagePath)
        imageView.image = image

有关详细信息,请查看http://helpmecodeswift.com/image-manipulation/saving-loading-images

  

此外,您实际上并没有使用在您的示例中选择的图像,正如Frederik指出的那样。

     

您保存一个尚未分配的空变量'img'。您需要保存“图像”,即拾取器完成后您获得的变量。

以下是获取图片的方式:

此函数返回变量'image'

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
picker.dismissViewControllerAnimated(true, completion: nil)
  

然后你可以继续使用它,例如

imageView.image = image  

或者

 saveImage(image, path: imagePath)  
祝你好运!

答案 1 :(得分:2)

使用此方法:使用如下图像参数:

 Yii::app()->db->createCommand()
    ->select('user_rights.region_id')
    ->from('user_rights')
    ->join('user_group', 'user_rights.user_group_id=user_group.user_group_id')
    ->queryAll();

答案 2 :(得分:1)

let fileDirectory : NSURL  = {
       return try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory , inDomain: .UserDomainMask , appropriateForURL: nil, create: true)
   }()


func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    picker.dismissViewControllerAnimated(true, completion: nil)

    //save to album 
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

   //or to documents 
   //If you want to use png you have to change it later in saveImageToDocumentMethod in the guard statement
   saveImageToDocuments(image, filenameWithExtension: "test.jpg")
}


func saveImageToDocuments(image: UIImage, fileNameWithExtension: String){

       let imagePath = fileDirectory.URLByAppendingPathComponent("\(fileNameWithExtension)")

       guard let imageData = UIImageJPEGRepresentation(image, 1) else {
           // handle failed conversion
           print("jpg error")
           return
       }
       imageData.writeToFile((imagePath.path)!, atomically: true)

   }

当您想要使用该图像时,您需要再次使用imagePath并将其转换为UIImage。