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

时间:2022-11-14 13:08:33

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 :

我有这段代码,我在获取图像路径时遇到了一个问题(我在谷歌中搜索并在flow上进行堆栈,但是我在objective-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 个解决方案

#1


2  

This code may help you:

这段代码可以帮助你:

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.

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

#1


2  

This code may help you:

这段代码可以帮助你:

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.

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