如何从swift中的照片库中获取图像或电影路径

时间:2015-07-12 14:31:47

标签: ios swift

我有这个代码,我在尝试获取图像路径时遇到问题:( 我搜索谷歌和堆栈流量,但我找到的解决方案是在客观c或代码不再在swift中工作:( 所以这是我的代码:

@IBAction func chooseWaterMark(sender: AnyObject) {
    var photoPicker = UIImagePickerController()
    photoPicker.delegate = self
    photoPicker.sourceType = .PhotoLibrary
    presentViewController(photoPicker, animated: true, completion: nil)

}

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
    waterMark.image = image
    waterMarkAlpha.image = image
    waterMarkAlpha.alpha = CGFloat(0.5)
    dismissViewControllerAnimated(false, completion: nil)


}

1 个答案:

答案 0 :(得分:2)

此代码可以帮助您:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL
    let imageName = imageURL.path!.lastPathComponent
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String
    let localPath = documentDirectory.stringByAppendingPathComponent(imageName)

    let image = info[UIImagePickerControllerOriginalImage] as UIImage
    let data = UIImagePNGRepresentation(image)
    data.writeToFile(localPath, atomically: true)

    let imageData = NSData(contentsOfFile: localPath)!
    let photoURL = NSURL(fileURLWithPath: localPath)
    let imageWithData = UIImage(data: imageData)!

    picker.dismissViewControllerAnimated(true, completion: nil)
}

使用此代码,您可以将图像保存到给定目录。希望它会有所帮助。