Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last frame from video?

Tags:

ios

swift

video

I want last frame of video and my code is shown below:

let asset : AVURLAsset = AVURLAsset(URL: videoURL, options: nil)
    let generate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
    generate.appliesPreferredTrackTransform = true

    var err : NSError? = nil
    var lastFrameTime = Int64(CMTimeGetSeconds(asset.duration))
    let time : CMTime = CMTimeMake(lastFrameTime, 30)
    let imgRef : CGImageRef = generate.copyCGImageAtTime(time, actualTime: nil, error: &err)
    let img : UIImage = UIImage(CGImage: imgRef)!

But I am not getting last frame , I am getting first frame, provide me solution for this.

like image 324
Pooja Shah Avatar asked Aug 17 '15 09:08

Pooja Shah


2 Answers

I used Pooja's code as a starting point but it doesn't get the last frame. it gets something close to the last frame. Here is my solution for getting the actual last frame. If frame accuracy is important, then you have to use:

imageGenerator.requestedTimeToleranceBefore = kCMTimeZero
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero

Be aware that it may take longer to generate this frame accurate last frame so you probably want to do it on a background thread.

Here is the code I am using:

let imageGenerator = AVAssetImageGenerator(asset: asset!)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero

let composition = AVVideoComposition(propertiesOfAsset: asset!)
let time = CMTimeMakeWithSeconds(asset!.duration.seconds, composition.frameDuration.timescale)

do {
    let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: nil)
}
catch let error as NSError {
    print("Image generation failed with error \(error)")
}

Hope this helps.

like image 102
Greg Veres Avatar answered Oct 01 '22 10:10

Greg Veres


You can get last frame of video in Objective-C as mentioned below:-

    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    AVAssetImageGenerator *generate = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    generate.appliesPreferredTrackTransform = YES;

    NSError *error;

    int64_t lastFrameTime = CMTimeGetSeconds(asset.duration)*60.0;
    CMTime time = CMTimeMake(lastFrameTime, 2);
    CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:nil error:&error];
    UIImage *image = [UIImage imageWithCGImage:imgRef];
like image 27
Asif Raza Avatar answered Oct 01 '22 08:10

Asif Raza