Getting thumbnail from video url or data


Video thumbnail IOS
Video thumbnail IOS

Getting thumbnail from a video url or data in iPhone is a easy task before IOS 7 as MPMoviePlayer provides us with a  method named thumbnailImageAtTime that gave us thumbnail of the video. But thumbnailImageAtTime method was deprecated in IOS 7. So to get thumbnail from our video url or data, we have to follow  a different approach.

NOTE: Swift version is also available get-thumbnail-from-video-url-in-swift

We will use AVURLAsset to get thumbnail from our video. For this we need AVFounadtion Framework and CoreMedia Framework. Below is the  code that will create a thumbnail for your video.
To create thumbnail, First import both frameworks to your viewController’s file using

#import
#import

Below method will return you a thumbnail image for your video

-(UIImage *)getThumbnailForVideoNamed:(NSString *)videoName ofType:(NSString *)videoType
{
       NSString *url=[[NSBundle mainBundle] pathForResource: videoName ofType:videoType];
       NSURL *videoURL = [NSURL fileURLWithPath:url];
      AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
      AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
      NSError *err = NULL;
      CMTime time = CMTimeMake(1, 2);
      CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
      UIImage *thumbNailImage = [[UIImage alloc] initWithCGImage:oneRef];
      return thumbNailImage;

}

Note: Please use UIViewContentModeScaleAspectFit contentMode for your UIImageView where you are showing thumbnail.

You can use above method as,

[self  getThumbnailForVideoNamed:@”Radha” ofType:@”.mp4″];

In case if you have Video as NSData then you have to first save that video data to document directory and then use that document directory as path. Below is the code  to save video data to document directory

 NSString* imagePath = [NSString stringWithFormat:@”%@/Video.mp4″,[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
 [[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
 [mediaData writeToFile:imagePath atomically:YES];

Note: mediaData is NSData object or our video as NSdata.