Creating Thumbnail for Video in iOS

前端 未结 5 1223
别跟我提以往
别跟我提以往 2020-12-05 03:12

I have an application that I am developing for the iPhone. What it does is, it captures the video from the camera and stores the video file onto the File System.

I

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 03:38

    Code for solution that uses AVFoundation framework and Swift 3.0 (commented code isn't necessary and is discussed below the code - you have to decide whether you need it or not):

    import AVFoundation
    
    func generateThumbnailForVideo(at url: URL) -> UIImage? {
        let kPreferredTimescale: Int32 = 1000
        let asset = AVURLAsset(url: url)
        let generator = AVAssetImageGenerator(asset: asset)
        generator.appliesPreferredTrackTransform = true
        //generator.requestedTimeToleranceBefore = kCMTimeZero
        //generator.requestedTimeToleranceAfter = kCMTimeZero
        //generator.maximumSize = CGSize(width: 100, height: 100)
    
        var actualTime: CMTime = CMTime(seconds: 0, preferredTimescale: kPreferredTimescale)
        //generates thumbnail at first second of the video
        let cgImage = try? generator.copyCGImage(at: CMTime(seconds: 1, preferredTimescale: kPreferredTimescale), actualTime: &actualTime)
        return cgImage.flatMap() { return UIImage(cgImage: $0, scale: UIScreen.main.scale, orientation: .up) }
    }
    

    Note that you may consider running this code on background thread as thumbnail creation can be potentially a costly operation.

    Also, please take a look at some of the properties of AVAssetImageGenerator class:

    1. requestedTimeToleranceBefore (Apple's documentation):

    The maximum length of time before a requested time for which an image may be generated.

    The default value is kCMTimePositiveInfinity.

    Set the values of requestedTimeToleranceBefore and requestedTimeToleranceAfter to kCMTimeZero to request frame-accurate image generation; this may incur additional decoding delay.

    1. requestedTimeToleranceAfter (Apple's documentation):

    The maximum length of time after a requested time for which an image may be generated.

    The default value is kCMTimePositiveInfinity.

    Set the values of requestedTimeToleranceBefore and requestedTimeToleranceAfter to kCMTimeZero to request frame-accurate image generation; this may incur additional decoding delay.

    1. maximumSize (Apple's documentation):

    Specifies the maximum dimensions for generated image.

    The default value is CGSizeZero, which specifies the asset’s unscaled dimensions.

    AVAssetImageGenerator scales images such that they fit within the defined bounding box. Images are never scaled up. The aspect ratio of the scaled image is defined by the apertureMode property.

提交回复
热议问题