如何将图像或视频从UIPickerViewController保存到文档目录?

时间:2015-11-25 12:33:26

标签: ios swift nsfilemanager

  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
    
  3. 如何将该图片保存到以下newPath

3 个答案:

答案 0 :(得分:11)

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

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

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

第2步:在路径

中追加FileName
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将视频保存到文档目录

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

答案 1 :(得分:6)

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

答案 2 :(得分:0)

快捷键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)
        }
     }