问题
Im using this to get a Preview thumbnail of a Video:
- (void)createThumb {
NSInteger paddingLeft = 22;
NSInteger paddingTop = 22;
CGFloat frameWidth = self.preview.frame.size.width - (2 * paddingLeft);
CGFloat frameHeight = self.preview.frame.size.height - (2 * paddingTop);
CGSize size = CGSizeMake(frameWidth, frameHeight);
MPMoviePlayerController *mp = [[MPMoviePlayerController alloc]
initWithContentURL:self.fileUrl];
NSLog(@"File url %@",self.fileUrl);
UIImage *thumbnail = [mp thumbnailImageAtTime:0.0
timeOption:MPMovieTimeOptionNearestKeyFrame];
[mp stop];
[mp release];
if (!thumbnail){
thumbnail = [UIImage imageNamed:@"video_dummy"];
}
thumb = [[thumbnail gtm_imageByResizingToSize:size preserveAspectRatio:YES trimToFit:NO] retain];
}
But it doesn't work. The resulting UIImage is always nil. Can someone help?
Thanks, Philip
回答1:
OK i found a solution:
Instead of using MPMoviePlayerController I use this, it does the job much better:
NSInteger paddingLeft = 24;
NSInteger paddingTop = 24;
CGFloat frameWidth = self.preview.frame.size.width - (2 * paddingLeft);
CGFloat frameHeight = self.preview.frame.size.height - (2 * paddingTop);
CGSize size = CGSizeMake(frameWidth, frameHeight);
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:self.fileUrl options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
[asset release];
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result == AVAssetImageGeneratorSucceeded) {
UIImage *thumbnail=[[UIImage imageWithCGImage:im] retain];
thumb = [[thumbnail gtm_imageByResizingToSize:size preserveAspectRatio:YES trimToFit:NO] retain];
NSData *thumbData = UIImageJPEGRepresentation(thumb, 0.2);
[thumbData writeToFile: [[[NSFileManager defaultManager] contentDirectory] stringByAppendingPathComponent:self.thumbFilename] atomically: NO];
[generator release];
[self.preview setImage: thumb];
}
else {
UIImage *thumbnail=[[UIImage imageNamed:@"video_dummy"] retain];
thumb = [[thumbnail gtm_imageByResizingToSize:size preserveAspectRatio:YES trimToFit:NO] retain];
NSData *thumbData = UIImageJPEGRepresentation(thumb, 0.2);
[thumbData writeToFile: [[[NSFileManager defaultManager] contentDirectory] stringByAppendingPathComponent:self.thumbFilename] atomically: NO];
[generator release];
[self.preview setImage: thumb];
}
};
CGSize maxSize = CGSizeMake(320, 180);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];
So if you want to do this use the AVFramework methods
来源:https://stackoverflow.com/questions/7178631/mpmovieplayercontrolle-thumbnailimageattime-timeoption-giving-empty-uiimage