I'm playing Video using AVPlayerLayer in a View. I need to convert View to Image, I tried
[myview.layer renderInContext:context];
but this gives only black image. I wanna convert that view into image with video on that time. This conversion will occur simultaneously 0.05s.
I tried with AVAssetImageGenerator. Which gives me the right image using Asset. But it taking little more time which makes some performance issue on my application. Can any one help me how to reduce the process of converting video to image for particular CMTime.
Below are my coding.
- (UIImage *)currentItemScreenShot
{
AVPlayer *abovePlayer = [objVC player];
if(imageGenerator == nil)
{
AVAsset *asset = [[[objVC player] currentItem] asset];
imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
}
CMTime time = [[abovePlayer currentItem] currentTime];
if ([imageGenerator respondsToSelector:@selector(setRequestedTimeToleranceBefore:)] && [imageGenerator respondsToSelector:@selector(setRequestedTimeToleranceAfter:)]) {
[imageGenerator setRequestedTimeToleranceBefore:kCMTimeZero];
[imageGenerator setRequestedTimeToleranceAfter:kCMTimeZero];
}
CGImageRef imgRef = [imageGenerator copyCGImageAtTime:time
actualTime:NULL
error:NULL];
if (imgRef == nil) {
if ([imageGenerator respondsToSelector:@selector(setRequestedTimeToleranceBefore:)] && [imageGenerator respondsToSelector:@selector(setRequestedTimeToleranceAfter:)]) {
[imageGenerator setRequestedTimeToleranceBefore:kCMTimePositiveInfinity];
[imageGenerator setRequestedTimeToleranceAfter:kCMTimePositiveInfinity];
}
imgRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
}
UIImage *image = [UIImage imageWithCGImage:imgRef];
CGImageRelease(imgRef);
image = [self reverseImageByScalingToSize:image.size :image];
return image;
}
The MPMoviePlayerController makes it easy to get a image from a movie at a certain point in the movie.
- (UIImage*)imageFromVideoAtPath:(NSString *)path atTime:(NSTimeInterval)time {
NSURL *videoURL = [NSURL fileURLWithPath:path];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
[moviePlayer prepareToPlay];
UIImage *thumbnail = [moviePlayer thumbnailImageAtTime:time timeOption:MPMovieTimeOptionNearestKeyFrame];
[moviePlayer stop];
return thumbnail;
}
Just call this with the path of the video, and at the time you want to get the image.
Please try below code. It is working perfectly for me.
And refer UIKit Function Reference.
+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
Also try this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With