抓取从UIImagePickerController保存的图像?

时间:2017-03-08 02:10:08

标签: ios swift uiimagepickercontroller uiimagejpegrepresentation

我试图从文档路径加载图片,在我的情况下显示为file:///var/mobile/Containers/Data/Application/AE7B9E43-E92D-4029-AE8D-4500CB61C15D/Documents/uploadImage.jpg。我如何获得该图像,以便可以使用POST调用发送出去?我是从imagePickerController保存图片的。这是我保存图像的代码......

    let fileDirectory : NSURL  = {
        return try! FileManager.default.url(for: .documentDirectory , in: .userDomainMask , appropriateFor: nil, create: true)
    }() as NSURL

    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    let imagePath = fileDirectory.appendingPathComponent("uploadImage.jpg")

    guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
        // handle failed conversion
        presentAlert(title: "Error", message: "Image Failure")
        print("jpg error")
        return
    }

    try! imageData.write(to: imagePath!
        print("Image Path: \(imagePath!)")

2 个答案:

答案 0 :(得分:1)

您可以使用

从文档路径获取图像
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
  if let dirPath  = documentPath.first{
    let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("uploadImage.jpg")
    let image    = UIImage(contentsOfFile: imageURL.path)
    // Do whatever you want with the image
  }

答案 1 :(得分:0)

将imagePath保存到某处。然后,您可以使用以下方式恢复图像:

func imageFromPath(path: String) -> UIImage? {
  if let data = NSData(contentsOfFile: path) {
    return UIImage(data: data)
  }
  return nil
}