如何将 UIPickerView 控制器中的图像或视频保存到文档目录?

How to save image or video from UIPickerViewController to document directory?

  1. 处理选定的图片或视频:

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        print("ok")
    
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //what to do to save that image
        } else {
            //how to get the video and save
        }
    }
    
  2. 保存到文档目录:

    let path = try! NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)
    let newPath = path.URLByAppendingPathComponent("image.jpg") //or video.mpg for example
    

如何将该图像保存到以下newPath

  • 使用以下步骤将图像保存到文档目录

步骤 1:获取文档目录的路径

let path = try! NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)

步骤 2:在路径中追加文件名

let newPath = path.stringByAppendingPathComponent("image.jpg")

第 3 步:确定图像的文件类型为 JPEG 或 PNG 并将图像转换为数据(字节)

//let pngImageData = UIImagePNGRepresentation(image) // if you want to save as PNG
let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG

步骤 4: 将文件写入创建的路径

let result = jpgImageData!.writeToFile(newPath, atomically: true)

将以上代码添加到您的 didFinishPickingImage 函数中。

  • 使用以下函数将视频保存到文档目录

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) 
    {
        // *** store the video URL returned by UIImagePickerController *** //
        let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
    
        // *** load video data from URL *** //
        let videoData = NSData(contentsOfURL: videoURL)
    
        // *** Get documents directory path *** //
        let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
    
        // *** Append video file name *** //
        let dataPath = documentsDirectory.stringByAppendingPathComponent("/videoFileName.mp4")
    
        // *** Write video file data to path *** //
        videoData?.writeToFile(dataPath, atomically: false)
    }
    

正在 Xcode 8.3.3

中更新对 Swift 3 的已接受答案
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
        let newPath = path.appendingPathComponent("image.jpg")
        let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
        do {
            try jpgImageData!.write(to: newPath)
        } catch {
            print(error)
        }

    } else {
        let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
        let videoData = NSData(contentsOf: videoURL as URL)
        let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
        let newPath = path.appendingPathComponent("/videoFileName.mp4")
        do {
            try videoData?.write(to: newPath)
        } catch {
            print(error)
        }
    }
}

Swift 5

func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        guard let image = info[.editedImage] as? UIImage else {
            print("No image found")
            return
        }
        // saving to application directory
        let imageName = UUID().uuidString
        let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)
        if let jpegData = image.jpegData(compressionQuality: 0.8) {
            print("Image Save to path \(imagePath)")
            try? jpegData.write(to: imagePath)
        }
     }