0

Hi i want to create a thumbnail from my video, is 2.46 minutes long and 68 Mb. I used this code to create the thumbnail :

AVAsset *asset = [AVAsset assetWithURL:videoURL];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = [asset duration];
time.value = 0;
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef); 

return thumbnail;

The issue is the thumbnail is always nil, but if i reduce the video length to 15 secs it will create the thumbnail. Can i create thumbnail for movie that more than 15 secs?

thanks

Voyager
  • 399
  • 1
  • 8
  • 15
  • Did you search? [this](http://stackoverflow.com/questions/19368513/generating-thumbnail-from-video-ios7) came up in my google-fu. – t0mm13b Oct 26 '15 at 02:06

1 Answers1

0

Mmmm this way to use AVAssetImageGenerator works:

AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:videoURL options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;

CGFloat videoLenght=((float)asset.duration.value)/((float)asset.duration.timescale);
CMTime thumbTime = CMTimeMakeWithSeconds(videoLenght,2.0);

AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
    if (result != AVAssetImageGeneratorSucceeded) {
        NSLog(@"couldn't generate thumbnail, error:%@", error);
    }else{
        UIImage *image=[self.class scaledImage:[UIImage imageWithCGImage:im]];
        [self performSelectorOnMainThread:@selector(setVideoImage:) withObject:image  waitUntilDone:NO];
    }
};

[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];  

(videoLenght,2.0) is the time where the snapshot takes place, in this case half of the video, I do not recommend you to use a fixed screenshot time because if the time is out of bounds the image will be nil.