私は、ユーザが録画したビデオのサムネイル画像をコレクションビューに設定しようとしています。映像が記録され、選択されると、この関数は、ディレクトリにサムネイル画像を保存するには、この機能を使用して...ドキュメントディレクトリへのビデオ...Stringファイルのパスから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 to documents directory
let thumbnailPath = saveImageToDocumentDirectory(UIImage(cgImage: videoImage))
// Add thumbnail & video path to Post object
let video = Post(pathToVideo: URL(fileURLWithPath: docDataPath), thumbnail: thumbnailPath)
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
}
}
問題は、UIImageセルのコレクションビューを保存したサムネイルで表示したいということです。上記のようにサムネイルがString
として保存されるPost
オブジェクトがあります。それはコレクションビューで細胞画像を設定することになるとだから、私はここにUIImageとしての私のオブジェクト(UIImageへの文字列のファイルパス)からサムネイルを使用するかどうかはわかりません。
cell.postImage.image = posts[indexPath.row].thumbnail
は誰をいこれを可能にする方法を知っていますか?
EDIT:画像を保存し、ファイルパスを取得するための更新機能:
func saveImageToDocumentDirectory(_ chosenImage: UIImage) -> URL {
let fm = FileManager.default
// Get date/time
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "ddhhmmss"
let now = dateFormatter.string(from: NSDate() as Date)
// Make the filename (String)
let filename = now.appending(".jpg")
let docsurl = try? fm.url(for:.documentDirectory, in: .userDomainMask,
appropriateFor: nil, create: false)
// Make the filepath
let filepath = docsurl?.appendingPathComponent(filename)
// Save filename to documents directory
do {
try UIImageJPEGRepresentation(chosenImage, 1.0)?.write(to: docsurl!, options: .atomic)
} catch {
print(error)
print("file cant not be save at path \(filepath), with error : \(error)");
// Return the filepath
return filepath!
}
}
とタイプURLであるとPost
オブジェクトにthumbnail
を変更しました。このような追加のポストオブジェクト:すべての
let thumbnailPath = saveImageToDocumentDirectory(UIImage(cgImage: videoImage))
let video = Post(pathToVideo: URL(fileURLWithPath: docDataPath), thumbnail: URL(fileURLWithPath: thumbnailPath))
問題は、彼がファイルパスを持っていないことです。彼は '/ Documents/\(filename)' 'を格納していますが、これはまったく間違っています。 – matt
私は@mattを知っているので、私はノートを追加しました – vadian
おかげでvadian 'UIImage(contentsOfFile ...')は私が理解しようとしていたものでしたmattが言ったように(そしてあなた)私は私はディレクトリにアクセスしています – KingTim