簡體   English   中英

我在Swift中創建了一個UIImage作為視頻的快照。 我如何獲得它的臨時路徑?

[英]I created a UIImage as a snapshot of my video in Swift. How can I get a temporary path to it?

所以我用了這段代碼:

func videoSnapshot(filePathLocal: String) -> UIImage? {

    let vidURL = NSURL(fileURLWithPath:filePathLocal as String)
    let asset = AVURLAsset(URL: vidURL)
    let generator = AVAssetImageGenerator(asset: asset)
    generator.appliesPreferredTrackTransform = true

    let timestamp = CMTime(seconds: 1, preferredTimescale: 60)

    do {
        let imageRef = try generator.copyCGImageAtTime(timestamp, actualTime: nil)
        return UIImage(CGImage: imageRef)
    }
    catch
    {
        print("Image generation failed with error \(error)")
        return nil
    }
}

從我的視頻中獲取快照的UIImage 我這樣調用此函數:

let tempImg: UIImage = videoSnapshot(pathToFile)!

現在,我想將此tempImg上傳到我的服務器,並且為此,我需要該文件的路徑-我稍后將其傳遞給進一步上傳數據的函數。 如何獲取它的臨時路徑並將其存儲為StringNSURL

您必須使用JPEG表示方法獲取圖像數據(選中復選框以使UIImageJPEGRepresentation回答),然后使用NSData方法writeToURL或writeToPath將其保存到磁盤。 對於臨時項目,可以使用URL appendingPathComponent方法在臨時文件夾url上創建目標url:

Swift 3看起來像這樣:

let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent("filename.jpg")
if let tempImg = videoSnapshot("filePathLocal"),
    let imgData = UIImageJPEGRepresentation(tempImg, 1) {
    do {
        try  imgData.write(to: destinationURL, options: .atomic)
        print("saved at:", destinationURL.path)
    } catch   {
        print(error.localizedDescription)
    }
}

迅捷2.3

if let tempImg = videoSnapshot("filePathLocal"),
    let imgData = UIImageJPEGRepresentation(tempImg, 1),
    let destinationURL = NSFileManager.defaultManager().temporaryDirectory.URLByAppendingPathComponent("filename.jpg")
    where imgData.writeToURL(destinationURL, atomically: true) {
    print("saved at:", destinationURL.path)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM