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

Posted

技术标签:

【中文标题】如何将 UIPickerViewController 中的图像或视频保存到文档目录?【英文标题】:How to save image or video from UIPickerViewController to document directory? 【发布时间】:2015-11-25 12:33:26 【问题描述】:

    处理选定的图像或视频:

    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
        
    
    

    保存到文档目录:

    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)

【讨论】:

我可以为视频做类似的事情吗?请用视频示例更新您的答案。 是的@BartłomiejSemańczyk 可以,我会更新我的答案。但是您需要使用视频选择器及其代表。相同的委托方法将不起作用。 最后一件事,我们怎么知道那个视频是什么扩展名?我们可以将它与mediaInfo 区别开来吗? 只有在 ios 设备中存储时才会是 .mp4 视频,但您可以从 mediaInfo 字典中的 UIImagePickerControllerMediaURL 中找到它。【参考方案2】:

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

【讨论】:

【参考方案3】:

斯威夫特 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)
        
     

【讨论】:

以上是关于如何将 UIPickerViewController 中的图像或视频保存到文档目录?的主要内容,如果未能解决你的问题,请参考以下文章

如何将Ios文件上传到

Qt如何将文字变成图片?

如何将Bitmap保存为本地图片文件?

在MATLAB中如何将图导出

ASP如何将SQLSERVER数据导出到DBF(VF)

如何将CSV格式转换成JSON格式