大佬教程收集整理的这篇文章主要介绍了ios – 如何将UIImage保存到文档目录?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
但是,只有视频路径在应用程序重新启动之间持续存在,因为它位于目录中,而缩略图则不然.我也想在那里保存缩略图,但我不知道如何去做,因为它似乎只能写入目录的URl.
这是我第一次使用文档目录,所以任何帮助将不胜感激!如何将缩略图(UIImage)与其来自的视频一起写入我的文档目录?
到目前为止,这是我的代码:
func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) { let mediaType = info[UIImagePickerControllerMediaType] as! NSString dismiss(animated: true,completion: nil) if mediaType == kUTTypeMovie { // Componenets for a unique ID for the video var uniqueVideoID = "" var videoURL:NSURL? = NSURL() var uniquEID = "" uniquEID = NSUUID().uuidString // Get the path as URL videoURL = info[UIImagePickerControllerMediaURL] as? URL as NSURL? let myVideoVarData = try! Data(contentsOf: videoURL! as URL) // Write the video to the Document Directory at myVideoVarData (and set the video's unique ID) let docPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,FileManager.SearchPathDomainMask.userDomainMask,truE) let documentsDirectory: AnyObject = docPaths[0] as AnyObject uniqueVideoID = uniquEID + "VIDEO.MOV" let docDataPath = documentsDirectory.appendingPathComponent(uniqueVideoID) as String try? myVideoVarData.write(to: URL(fileURLWithPath: docDataPath),options: []) print("docDataPath under picker ",docDataPath) print("Video saved to documents directory") // Create a thumbnail image from the video (first framE) let asset = AVAsset(url: URL(fileURLWithPath: docDataPath)) let assetImageGenerate = AVAssetImageGenerator(asset: asset) assetImageGenerate.appliesPreferredTrackTransform = true let time = CMTimeMake(asset.duration.value / 3,asset.duration.timescalE) if let videoImage = try? assetImageGenerate.copyCGImage(at: time,actualTime: nil) { // Add thumbnail & video path to Post object let video = Post(pathToVideo: URL(fileURLWithPath: docDataPath),thumbnail: UIImage(cgImage: videoImagE)) posts.append(video) print("Video saved to Post object") } } }
func saveImageToDocumentDirectory(_ chosenImage: UIImagE) -> String { let directoryPath = NSHomeDirectory().appending("/Documents/") if !FileManager.default.fileExists(atPath: directoryPath) { do { try FileManager.default.createDirectory(at: NSURl.fileURL(withPath: directoryPath),withIntermediateDirectories: true,attributes: nil) } catch { print(error) } } let filename = NSDate().String(withDateFormatter: yyyytoss).appending(".jpg") let filepath = directoryPath.appending(fileName) let url = NSURl.fileURL(withPath: filepath) do { try UIImageJPEGRepresentation(chosenImage,1.0)?.write(to: url,options: .atomiC) return String.init("/Documents/\(fileName)") } catch { print(error) print("file cant not be save at path \(filepath),with error : \(error)"); return filepath } }
一个建议:如果可以按照苹果的指南再次下载图像,则将图像保存到库/缓存中.
以上是大佬教程为你收集整理的ios – 如何将UIImage保存到文档目录?全部内容,希望文章能够帮你解决ios – 如何将UIImage保存到文档目录?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。