📜 ⬆️ ⬇️

Retrieving and caching screenshots from video by URL

Hello, habrazhitel!

In this small article, I want to again share my experience with video in one of the latest projects for iOS. This time it will be about getting a screenshot from the video.



On the Internet, I met several solutions to this problem, but they were all implemented via MPMoviePlayerController . Yes, this is a solution, but I want to talk about another, perhaps more correct solution that works faster and is great for low-speed mobile Internet.
')
In solving this problem, we need only two things: the standard AVAssetImageGenerator class and just a great project on the githab, which many people know about, called SDWebImage .

First we get a picture using AVAssetImageGenerator

NSURL *videoURL = [NSURL URLWithString:@"video_url"] AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil]; AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset]; NSError *error; CGImageRef imageRef = [generator copyCGImageAtTime:CMTimeMake(1, 2) actualTime:NULL error:&error]; if (!error) { UIImage *image = [[UIImage alloc] initWithCGImage:ref]; } 

Now in the image variable we have a picture that can be shown, and it would also be nice to put it in the cache. SDImageCache will help us with this task.

To put an image into the cache, you need to form a key, according to which we will then take it out from there, and call only one function

 NSString *imageCacheKey = [[@"video_url" lastPathComponent] stringByDeletingPathExtension]; [[SDImageCache sharedImageCache] storeImage:image forKey:imageCacheKey]; 


To get the picture is also quite simple

 [[SDImageCache sharedImageCache] queryDiskCacheForKey:imageCacheKey done:^(UIImage *image, SDImageCacheType cacheType) { if (image) { } }]; 

In the block it is necessary to check the image on nil. I think no need to explain why :).

That's all, you can add a picture of a couple of effects to your taste, for example, a smooth appearance through animateWithDuration

 self.photo.image = image; [UIView animateWithDuration:0.25 animations:^{ self.photo.alpha = 1.f; }]; 


Thank you all for your attention, I will try to answer all the questions in the comments, you can take a working example here: https://github.com/Borodutch/BSVideoThumbnails

Source: https://habr.com/ru/post/240231/


All Articles