Generating Video Thumbnail for .mov file objective C - ios

I'm trying to generate a thumbnail image and save it to a file. This it's my code.
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:object[#"path"] options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSError *err = NULL;
CMTime requestedTime = CMTimeMake(1, 60); // To create thumbnail image
CGImageRef imgRef = [generator copyCGImageAtTime:requestedTime actualTime:NULL error:&err];
NSLog(#"err = %#, imageRef = %#", err, imgRef);
UIImage *thumbnailImage = [[UIImage alloc] initWithCGImage:imgRef];
CGImageRelease(imgRef);
NSString* path = [NSHomeDirectory() stringByAppendingString:#"/Documents/myImage.png"];
BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
contents:nil attributes:nil];
if (!ok)
{
NSLog(#"Error creating file %#", path);
}
else
{
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(thumbnailImage)];
[myFileHandle closeFile];
resolve(path);
}
But I'm getting this error:
Code=-11822 "Cannot Open" UserInfo={NSLocalizedDescription=Cannot Open, NSLocalizedFailureReason=This media format is not supported.}
Any thoughts?

Related

Not getting the value in asset when loading the video from gallery using ALAssetLibrary

I want to display the thumbnail of videos by using ALAssetLibrary and for displaying the video from gallery to my app , i filtered all videos from ALAssetsFilter .
But still i am getting the null value in asset of type ALAsset.
Please tell me what i am doing wrong with my code.
Appreciate for the help.
-(void)loadAssets{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *innerStop) {
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[allVideos addObject:asset];
}
}];
[_collectionView reloadData];
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
}
- (UIImage *)imageFromVideoURL:(NSURL*)videoURL
{
UIImage *image = nil;
AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];;
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
// get the image from
NSError *error = nil;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
// cgimage to uiimage
image = [[UIImage alloc] initWithCGImage:halfWayImage];
[dic setValue:image forKey:#"ImageThumbnail"];//kImage
NSLog(#"Values of dictonary==>%#", dic);
NSLog(#"Videos Are:%#",allVideos);
CGImageRelease(halfWayImage);
}
return image;
}
Use this code may this will help you to generate thumbnail image-- -
-(UIImage*)loadImage {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.videoURL options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generate.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
return [[UIImage alloc] initWithCGImage:imgRef];
}
I have Create the Thumbnail image from Video, its working for me and the code is below,
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"store url %#",videoURL);
AVAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
if ([[avAsset tracksWithMediaType:AVMediaTypeVideo] count] > 0)
{
AVAssetImageGenerator *imageGenerator =[AVAssetImageGenerator assetImageGeneratorWithAsset:avAsset];
Float64 durationSeconds = CMTimeGetSeconds([avAsset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
NSError *error;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:kCMTimeZero actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
NSString *actualTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));
NSString *requestedTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, midpoint));
NSLog(#"Got halfWayImage: Asked for %#, got %#", requestedTimeString, actualTimeString);
UIImage *img=[UIImage imageWithCGImage:halfWayImage];
playButton.hidden=NO;
self.myimageView.image= img; //[self scaleImage:img maxWidth:(img.size.width/5) maxHeight:(img.size.height/5)];
}
}
Finally got the thumbnail image, hope its helpful

Objective-c, Is there any way fetch video thumbnail from URL instead using MPMoviePlayerController and AVAssetImageGenerator?

I want to fetch video thumbnail from URL instead using MPMoviePlayerController and AVAssetImageGenerator. Because these have some issue. Issue I have already asked,
1st one is : AVAssetImageGenerator not working properly, I am unable to fetch thumbnail of video from URL
and 2nd is : https://stackoverflow.com/questions/32431311/mpmovieplayercontroller-not-fetching-thumbnail-of-video-from-url-properly
I have no idea how to do it. Any suggestion will be great. Thank in advance !!!
All you need is to put into comment below your URL and self.imageView.image = FrameImage;
Anyway.
NSString *str=#"https://scontent.cdninstagram.com/hphotos-xfa1/t50.2886-16/11719145_918467924880620_816495633_n.mp4";
NSURL *url=[[NSURL alloc]initWithString:str];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
NSError *error = NULL;
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);
CGImageRef refImg = [generator copyCGImageAtTime:thumbTime actualTime:NULL error:&error];
if(error) {
NSLog(#"%#", [error localizedDescription]);
}
UIImage *FrameImage= [[UIImage alloc] initWithCGImage:refImg];
[self.imageView setImage:FrameImage];
Try this one.
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:#"[video URL]"] options:nil];
AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSError *error = NULL;
CMTime time = CMTimeMake(1, 65);
CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&error];
NSLog(#"error==%#, Refimage==%#", error, refImg);
UIImage *FrameImage= [[UIImage alloc] initWithCGImage:refImg];

Video thumbnail does not appear in collection view

self.url = [self grabFileURL:#"video.mov"];
NSLog(#"The URL is: %#", self.url);
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:self.url 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 *one = [[UIImage alloc] initWithCGImage:oneRef];
CaptureViewController *cv = [[CaptureViewController alloc]init];
[cv.thumbnail setImage:one];
NSLog(#"The thumbnail is: %#", one);
one = [UIImage imageNamed:#"vid.png"];
videoGallery = [NSArray arrayWithObjects:#"vid.png", nil];
Edit:
- (NSURL*)grabFileURL:(NSString *)fileName {
// find Documents directory
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
// append a file name to it
documentsURL = [documentsURL URLByAppendingPathComponent:fileName];
return documentsURL;
}
No output error in NSLog but the thumbnail still doesn't show up in collection view controller. What have I missed ?
-(void)generateImageForImageView:(UIImageView *) imageView withURL:(NSString *) VideoURL
{
NSURL *url = [NSURL URLWithString:VideoURL];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = [asset1 duration];
time.value = 0;
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
[imageView setImage:one];
imageView.contentMode = UIViewContentModeScaleToFill;
}
use this method hope it will be useful to you, its work for me

thumbnail of a video on clicking video file in iOS simulator

I have a video in gallery. on clicking it tries to open,but instead of that i want to show a thumbnail of video in uiimageview.
AVURLAsset *asset;
if ([url isFileURL]) {
asset = [[AVURLAsset alloc] initWithURL:url options:nil];
}
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
gen.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(0.0, 600);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
UIImage *finalThumpnailImage = [HPLUtility createThumpnailImageFromTheImage:thumb]; //Resized image.
CGImageRelease(image);
return finalThumpnailImage;

set image size for thumbnail image generated using AVAssetImageGenerator ios

I was using AVAssetImageGenerator class for generating thumbnail image but problem is i need to fit that thumbnail image into UITableViewCell having UIImageView of size (320,239).
I specified AVAssetImageGenerator maximum size property as (320,239) but i was not getting desired size what i specified please any help thanks in advance. Please look at the following code for quick reference.
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.consenteeVideoUrl options:nil];
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
gen.maximumSize = CGSizeMake(320, 239);
gen.apertureMode = AVAssetImageGeneratorApertureModeProductionAperture;
gen.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(0.0, 600);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *thumbnailImage = [[UIImage alloc] initWithCGImage:image];
//thumbnailImage = [CSUtilities imageWithImage:thumbnailImage scaledToSize:CGSizeMake(320, 239)];
CGImageRelease(image);
One more solution i got from "stackoverflow" but not much helpful in my scenario.`
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:self.consenteeVideoUrl options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
CMTime thumbTime = CMTimeMakeWithSeconds(30,30);
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result != AVAssetImageGeneratorSucceeded) {
NSLog(#"couldn't generate thumbnail, error:%#", error);
}
UIImage *thumbnailImage = [[UIImage alloc] initWithCGImage:im];
//save image to application directory...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:self.uniqueCodeString];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *savedImagePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",self.uniqueCodeString]];
NSData *imageData = UIImagePNGRepresentation(thumbnailImage);
BOOL success = [imageData writeToFile:savedImagePath atomically:YES];
if (success) {
CSLog(#"sucess");
}
partnerEvent.thumbnailImageStr = [self getImagePath];
[self.ibPartnerEventTableView reloadData];
};
CGSize maxSize = CGSizeMake(320, 239);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];
Nothing is wrong in your code, but as stated in the documentation
AVAssetImageGenerator scales images such that they fit within the
defined bounding box. Images are never scaled up. The aspect ratio of
the scaled image is defined by the apertureMode property.
Since the apertureMode is set to AVAssetImageGeneratorApertureModeProductionAperture images generated keeps the aspect ratio. it will only fit the maximum size if the the video and the size set have the same aspect ratio, and this will unlikely to happen with the size specified.
Try to change the UIImageView contentMode to UIViewContentModeScaleAspectFill some content could be cropped but you will fill the entire imageView

Resources