如何从swift中的照片库中获取图像或电影路径
问题描述:
我有这个代码而且我在尝试获取图像路径时遇到了问题:(
我在google搜索并堆栈流过但是我发现的解决方案是在objective-c或代码中没有'在swift中再工作:(
所以这是我的代码:
I have this code and I'm having a problem trying to get the image path :( I searched in google and stack over flow but the solution that I found were in objective-c or code that doesn't work anymore in swift :( so this is my code :
@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)
}
答
此代码可以帮助您:
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)
}
使用此代码,您可以将图像保存到给定目录。希望它会有所帮助。
With this code you can save image to the given directory. Hope it will help.