web-dev-qa-db-ja.com

UIImagePickerControllerから選択されたUIImageのURLを取得する

フォトライブラリからユーザーが選択した画像を提供しようとしています。したがって、選択には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を記述していますが、ファイルシステムのURLは記述していません。そして次のようになります:assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG

このロジックによれば、path is /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を使用していくつかのチュートリアルを調べましたが、問題を解決するのに役立つものは見つかりませんでした。前もって感謝します!

14
Majotron

さて、私は問題を解決しました。

あなたがしなければならないのは、単に画像をつかむことです(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)

}
32
Majotron

Swift 4 uこれを試すことができます、それは正常に動作しています。

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)
}
9
Jaydip
  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)
 }
4
DHuang

このソリューションを確認してください。

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

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

    }

}
1
king_T

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

ありがとう

1
V D Purohit
let imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL
0
Ankit Gabani