我在Swift中创建了一个UIImage作为我视频的快照。我怎样才能获得临时路径?

时间:2016-09-20 19:35:51

标签: ios swift uiimage

所以我使用了这段代码:

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

1 个答案:

答案 0 :(得分:1)

您必须使用JPEG表示方法获取图像数据(检查this以便UIImageJPEGRepresentation回答)并使用NSData方法writeToURL或writeToPath将其保存到磁盘。对于临时项目,您可以使用URL appendingPathComponent方法在temporary folder 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)
    }
}

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