如何在swift中从照片库中获取图片或影片路径[英] How to get the image or movie path from the photo Library in swift

本文是小编为大家收集整理的关于如何在swift中从照片库中获取图片或影片路径的处理方法,想解了如何在swift中从照片库中获取图片或影片路径的问题怎么解决?如何在swift中从照片库中获取图片或影片路径问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我有这段代码,但在尝试获取图像路径时遇到问题:(我在 google 和 stack over 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)


}

推荐答案

这段代码可以帮到你:

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)
}

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

本文地址:https://www.itbaoku.cn/post/924525.html