【问题标题】:UIImagePickerController get Image URL with SwiftUIImagePickerController 使用 Swift 获取图像 URL
【发布时间】:2016-05-18 10:48:50
【问题描述】:

我有一个UIImagePickerController 让用户选择一张图片,因为我想上传这张图片,所以我需要图片“localURL”。 有没有办法从我的选择器中获取这个 localURL。

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    imagePicker.delegate = self
}

@IBAction func loadImageButtonTapped(sender: AnyObject) {
    imagePicker.allowsEditing = false
    imagePicker.sourceType = .PhotoLibrary
    presentViewController(imagePicker, animated: true, completion: nil)
}


func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.contentMode = .ScaleAspectFit
        imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)
}


func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
}

【问题讨论】:

    标签: ios swift image file


    【解决方案1】:

    由于您无权访问应用容器之外的图像,因此您不会获得任何本地 url。

    您不需要传输图像的文件,NSData 应该完全没问题。我建议你像这样把它转换成NSData

    let imageData: NSData = UIImagePNGRepresentation(pickedImage)
    

    更新:正如我所说,您将无法访问实际文件。将图像作为文件的唯一方法是自己存储。

    在您的更新中,您展示了一些用于自己保存图像的代码,这是有道理的。如果在设置“imageView.image”时使用“pickedImage”而不是写入图像文件并读取它,将其转换为“UIImage”,然后将其设置为“imageView.image”,性能会更高

    我还没有真正弄清楚,为什么您需要将图像作为文件而不是简单地将“NSData”发送到您的服务器。也许这是一个值得你考虑的选择

    【讨论】:

    • 您的解决方法(顺便说一句,您应该在问题中将其发布为编辑)并不是很有效,因为您正在写入文件,然后再次读取图像以获取图像视图 - 而您仍然可以访问thepickImage 你能解释一下,为什么你特别需要图像作为文件吗?
    • 我需要它作为文件,因为我选择后通过 SSH 将它上传到服务器
    • 我更新了我的答案。仍然不明白为什么您不能将 NSData 发送到您的服务器,但也许有一些特殊情况。因为通常,nsdata 是要走的路
    【解决方案2】:

    作为解决方法,我确实保存了图像,

      if let data = UIImageJPEGRepresentation(pickedImage, 0.8) {
                    let filename = getDocumentsDirectory().stringByAppendingPathComponent("image.jpg")
                    data.writeToFile(filename, atomically: true)
                    print("file saved as image.jpg")
                    print(filename)
    
                    var image = UIImage(contentsOfFile: filename)
                    imageView.image = image
    
                }
    

    【讨论】:

      猜你喜欢
      • 2015-09-06
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多