ios 获取从 UIImagePickerController 中选择的 UIImage 的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28255789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:37:23  来源:igfitidea点击:

Getting URL of UIImage selected from UIImagePickerController

iosswiftios8uiimagepickercontrollernsurl

提问by mozharovsky

I'm trying to provide a user selection of an image from Photo Library. Thus I'm using UIImagePickerControllerfor selecting. But here comes an issue with getting its initial URL in the file system (I need this for CKAsset).

我正在尝试提供用户从照片库中选择的图像。因此我UIImagePickerController用于选择。但是在文件系统中获取其初始 URL 时出现了一个问题(我需要这个用于CKAsset)。

My code.

我的代码。

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

    let imageData = NSData(contentsOfFile: localPath)!
    let image = UIImage(data: imageData)!

    picker.dismissViewControllerAnimated(true, completion: nil)

}

imageURLis kinda cryptic. It describes Asset URL, but not one in File System. And it looks like: assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG.

imageURL有点神秘。它描述了资产 URL,但不是文件系统中的 URL。它看起来像:assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG

According to this logic the pathis /asset.JPGwhere asset.JPGis a name of the image.

根据该逻辑路径/asset.JPG其中asset.JPG是所述图像的名称。

Then I'm accessing my Documents folder and trying to find there a file with path:

然后我访问我的 Documents 文件夹并尝试在那里找到一个带有路径的文件:

/Users/Eugene/Library/Developer/CoreSimulator/Devices/3C5E9A23-8220-4B37-BD14-F1E42EEC2C7C/data/Containers/Data/Application/20EBAAE2-6C6F-4651-A48F-16A222CCB3A2/Documents/asset.JPG

/Users/Eugene/Library/Developer/CoreSimulator/Devices/3C5E9A23-8220-4B37-BD14-F1E42EEC2C7C/data/Containers/Data/Application/20EBAAE2-6C6F-4651-A48F-16A22/JPCCB3D

Cryptic as well but seems to be a real path for a not existing image... No image with that path can be found. And this makes me sick.

也很隐秘,但似乎是不存在图像的真实路径...找不到具有该路径的图像。这让我感到恶心。

Do I have to save an image from the beginning? Or is there any other way to go?

我必须从一开始就保存图像吗?或者还有什么其他方法可以去?

I've looked through several tutorials using AssetsLibraryAPI but I didn't find anything useful to solve my problem. Thank you in advance!

我已经使用AssetsLibraryAPI浏览了几个教程,但没有找到任何有用的东西来解决我的问题。先感谢您!

回答by mozharovsky

Okay, I've solved the issue.

好的,我已经解决了这个问题。

All you have to do is simply grab the image (info[UIImagePickerControllerOriginalImage] as UIImage) and save to the given directory. If you need to save only 1 picture it works great. The code id below.

您所要做的就是简单地抓取图像 ( info[UIImagePickerControllerOriginalImage] as UIImage) 并保存到给定的目录中。如果您只需要保存 1 张图片,它效果很好。下面的代码id。

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)

}

回答by Jaydip

In SWIFT 4u Can Try This, It's working properly.

SWIFT 4 中你可以试试这个,它工作正常。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {


    if let imgUrl = info[UIImagePickerControllerImageURL] as? URL{
        let imgName = imgUrl.lastPathComponent
        let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let localPath = documentDirectory?.appending(imgName)

        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let data = UIImagePNGRepresentation(image)! as NSData
        data.write(toFile: localPath!, atomically: true)
        //let imageData = NSData(contentsOfFile: localPath!)!
        let photoURL = URL.init(fileURLWithPath: localPath!)//NSURL(fileURLWithPath: localPath!)
        print(photoURL)

    }

    APPDEL.window?.rootViewController?.dismiss(animated: true, completion: nil)
}

回答by DHuang

  func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
//this block of code grabs the path of the file   
let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL
let imagePath =  imageURL.path!
let localPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(imagePath)

 //this block of code adds data to the above path
 let path = localPath.relativePath!
 let imageName = info[UIImagePickerControllerOriginalImage] as UIImage
 let data = UIImagePNGRepresentation(imageName)
 data?.writeToFile(imagePath, atomically: true)

//this block grabs the NSURL so you can use it in CKASSET
 let photoURL = NSURL(fileURLWithPath: path)
 }

回答by TMD

check this solution.

检查此解决方案。

 import AssetsLibrary  

     func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
          self.imagePicker = picker
          if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            let controller = CropViewController(image: selectedImage )
            controller.delegate = self
            picker.presentViewController(controller, animated: true, completion: nil)
          }

       else if let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL{
          let assetLibrary = ALAssetsLibrary()
          assetLibrary.assetForURL(imageUrl , resultBlock: { (asset: ALAsset!) -> Void in
            if let actualAsset = asset as ALAsset? {
              let assetRep: ALAssetRepresentation = actualAsset.defaultRepresentation()
              let iref = assetRep.fullResolutionImage().takeUnretainedValue()
              let image = UIImage(CGImage: iref)
              let controller = CropViewController(image: image)
              controller.delegate = self
              picker.presentViewController(controller, animated: true, completion: nil)
            }
            }, failureBlock: { (error) -> Void in
          })
        }
      }

回答by king_T

In swift 4

在迅速 4

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {        
    if let imgUrl = info[UIImagePickerControllerReferenceURL] as? URL{

        let imgName = imgUrl.lastPathComponent
        let documentDirectory = NSTemporaryDirectory()
        let localPath = documentDirectory.appending(imgName)

        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let data = UIImageJPEGRepresentation(image, 0.3)! as NSData
        data.write(toFile: localPath, atomically: true)
        let photoURL = URL.init(fileURLWithPath: localPath)

    }

}

回答by V D Purohit

swift 4.2

快速 4.2

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    //obtaining saving path
    let fileManager = FileManager.default
    let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
    let imagePath = documentsPath?.appendingPathComponent("image.jpg")

    // extract image from the picker and save it
    if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {

        let imageData = pickedImage.jpegData(compressionQuality: 0.75)
        try! imageData?.write(to: imagePath!)
    }
}

Thanks

谢谢

回答by Ankit Gabani

let imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL

回答by Hannes Schaletzky

For Swift 5+ ;according to @Jaydip answer

对于 Swift 5+ ;根据@Jaydip 的回答

if let imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL{
        let imgName = imgUrl.lastPathComponent
        let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let localPath = documentDirectory?.appending(imgName)

        let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        let data = image.pngData()! as NSData
        data.write(toFile: localPath!, atomically: true)
        //let imageData = NSData(contentsOfFile: localPath!)!
        let photoURL = URL.init(fileURLWithPath: localPath!)//NSURL(fileURLWithPath: localPath!)
        print(photoURL)

    }