gpt4 book ai didi

ios - 如何将 UIImage 保存到文档目录?

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:19 28 4
gpt4 key购买 nike

我正在尝试将录制视频的文件路径和视频的缩略图保存到文档目录中。然后,使用文件路径将这两个值设置为一个对象,这样我就可以使用该对象来填充 Collection View 。使用我目前(下面)的代码,在我录制视频后,视频路径被保存到文档目录,视频路径和缩略图被设置到我的 Post 对象,缩略图出现在我的收藏 View 中正确。到目前为止一切都很好。

但是,只有视频路径在应用程序重新启动之间持续存在,因为它在目录中,而缩略图不在。我也想在那里保存缩略图,但我不知道该怎么做,因为您似乎只能将 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")
}
}
}

最佳答案

一个建议:如果可以按照 apple 的指南再次下载图像,则将图像保存到库/缓存。


就这么简单:

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

swift 4:

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 dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddhhmmss"

let filename = dateFormatter.string(from: Date()).appending(".jpg")
let filepath = directoryPath.appending(filename)
let url = NSURL.fileURL(withPath: filepath)
do {
try chosenImage.jpegData(compressionQuality: 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 保存到文档目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016666/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com