获取从 UIImagePickerController 中选择的 UIImage 的 URL

Posted

技术标签:

【中文标题】获取从 UIImagePickerController 中选择的 UIImage 的 URL【英文标题】:Getting URL of UIImage selected from UIImagePickerController 【发布时间】:2015-03-31 02:28:52 【问题描述】:

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

我的代码。

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)


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

根据这个逻辑,路径/asset.JPG,其中asset.JPG是图像的名称。

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

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

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

我必须从头开始保存图像吗?或者有没有其他方法可以走?

我浏览了几个使用 AssetsLibrary API 的教程,但没有发现任何有用的东西可以解决我的问题。提前谢谢!

【问题讨论】:

【参考方案1】:

对于 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)

    

【讨论】:

感谢兄弟的工作【参考方案2】:
let imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL

【讨论】:

【参考方案3】:

斯威夫特 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!)
    

谢谢

【讨论】:

【参考方案4】:

在 Swift 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)

    


【讨论】:

仅供参考 - 自 ios 11.0 起,UIImagePickerController.InfoKey.referenceURL 已被弃用。【参考方案5】:

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)

【讨论】:

适用于 iOS +11.0【参考方案6】:

检查此解决方案。

 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
          )
        
      

【讨论】:

【参考方案7】:
  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)
 

【讨论】:

@Peter Kreinz,希望这个对您有所帮助【参考方案8】:

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

您所要做的只是获取图像 (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)


【讨论】:

您能否更新您对 Swift 2 的回答?谢谢! 在 Swift 3 中不起作用,我转换了代码使其可以编译,但返回的路径不指向所选图像 对于 Swift 3,检查这个解决方案:***.com/questions/4957972/… @majorton 保存 100 张图片的最佳方法是什么?

以上是关于获取从 UIImagePickerController 中选择的 UIImage 的 URL的主要内容,如果未能解决你的问题,请参考以下文章

如何调整自定义 UIButton 的图像大小?

imageWithData图像尺寸变大了?

Segue 图像到另一个视图控制器的问题

imagePickerController 选择照片时出错

iPhone - 以编程方式删除状态栏

获取OpenHarmony源码:从DevEco Marketplace获取