Generating thumbnail from video - ios7 - objective-c

I am using this for reference: Getting thumbnail from a video url or data in IPhone SDK
The method is using the MPMoviePlayerController class instead of the AVFoundation, and I think I want to use that as well because the people said that MPMoviePlayer way is faster than the AVFoundation way.
The problem is, the method used to create the thumbnails, [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame] is deprecated in iOS 7.0.
By looking at the apple docs, the remaining supported ways to create thumbnails are by the methods (void)requestThumbnailImagesAtTimes:(NSArray *)playbackTimes timeOption:(MPMovieTimeOption)option and (void)cancelAllThumbnailImageRequests. But, as the method signatures dictate, these methods return nothing. So how do I access the UIImage thumbnail created by these methods?
If it helps, this is what I have so far in terms of code:
self.videoURL = info[UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:self.videoURL];
//Create thumbnail image
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:self.videoURL];
[player requestThumbnailImagesAtTimes:#[#1] timeOption:MPMovieTimeOptionNearestKeyFrame];
//UIImage *thumbnail = ???
How do I get a UIImage reference to the thumbnail?
EDIT
I figured out how to create a notification for the thumbnail image request (using this question as reference). However, I realise that this method works asynchronously from the main thread, and so my notification handler method doesn't seem to ever be called.
This is what I have now.
self.videoURL = info[UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:self.videoURL];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:self.videoURL];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleThumbnailImageRequestFinishNotification:) name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:player];
[player requestThumbnailImagesAtTimes:#[#1] timeOption:MPMovieTimeOptionNearestKeyFrame];
And then my handler method:
-(void)handleThumbnailImageRequestFinishNotification:(NSNotification*)notification
{
NSDictionary *userinfo = [notification userInfo];
NSError* value = [userinfo objectForKey:MPMoviePlayerThumbnailErrorKey];
if (value != nil)
{
NSLog(#"Error creating video thumbnail image. Details: %#", [value debugDescription]);
}
else
{
UIImage *thumbnail = [userinfo valueForKey:MPMoviePlayerThumbnailImageKey];
}
But the handler never gets called (or so it appears).

Try this way.
import AVFoundation framework
in *.h
#import <AVFoundation/AVFoundation.h>
in *.m
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.urlForConevW 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];

Here is a code to make a thumbnail of the video and save the images to the DocumentDirectory..
//pass the video_path to NSURL
NSURL *videoURL = [NSURL fileURLWithPath:strVideoPath];
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generator.appliesPreferredTrackTransform = YES;
//Set the time and size of thumbnail for image
NSError *err = NULL;
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);
CGSize maxSize = CGSizeMake(425,355);
generator.maximumSize = maxSize;
CGImageRef imgRef = [generator copyCGImageAtTime:thumbTime actualTime:NULL error:&err];
UIImage *thumbnail = [[UIImage alloc] initWithCGImage:imgRef];
//And you can save the image to the DocumentDirectory
NSData *data = UIImagePNGRepresentation(thumbnail);
//Path for the documentDirectory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[data writeToFile:[documentsDirectory stringByAppendingPathComponent:currentFileName] atomically:YES];

If your URL is to an HTTP live stream, then it won't return anything, per the docs. For a file URL, I found that I had to start the request after playing the movie, or it would never get called.

Related

How can I share a gif image using UIActivityViewController with Objective-C?

I have an app that lets the user record a short video and generate a gif image. Now I want to give the user the possibility to share that gif image using UIActivityViewController, I've done this:
UIImage *img = ...
NSArray *objectsToShare = #[img];
UIActivityViewController *avc = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypePrint];
avc.excludedActivityTypes = excludeActivities;
[self presentViewController:avc animated:YES completion:nil];
The problem is that this only shares an static .jpg image (like the first frame of the original .gif image).
On the other hand, the user can save the gif image to the camera roll, and from there it is possible to share it as a .gif. So how can I do the same thing but from my own app?
Thanks in advance.
Ok, I managed to do this, and now I can share gif images by email, but I thing there is something left to do with Twitter.
UIImage *img = ...;
NSError *err;
NSData *imgData = [imageSerialization animatedGIFDataWithImage:img error:&err];
NSLog(#"%#", err);
NSArray *objectsToShare = #[imgData];
UIActivityViewController *avc = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypePrint, UIActivityTypeAssignToContact];
avc.excludedActivityTypes = excludeActivities;
[self presentViewController:avc animated:YES completion:nil];
Share GIF File For WhatsApp:
NSURL *imageUrl =[self.ImageArray objectAtIndex:currentPhotoIndex];
NSString *path=imageUrl.absoluteString;
NSArray *strings = [path componentsSeparatedByString:#"/"];
NSString *mygif=[strings objectAtIndex:strings.count-1];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dataPath = [documentsPath stringByAppendingPathComponent:#"/MrHRamani"];
NSString *filePath = [dataPath stringByAppendingPathComponent:mygif];
NSURL *urll=[NSURL fileURLWithPath:filePath];
NSLog(#"imag %#",imageUrl);
self.documentationInteractionController.delegate = self;
self.documentationInteractionController.UTI = #"net.whatsapp.image";
self.documentationInteractionController = [self setupControllerWithURL:urll usingDelegate:self];
[self.documentationInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

Background thread returning result of UIImage as nil

This only happens when the Entry has been created on this run of the app. If the Entry is previously created, it fetches the image fine.
This code works fine without using background threads, so it leads me to believe it to be part of the problem. Here's the code I have:
NSMutableDictionary *thumbnails = [[NSMutableDictionary alloc] init];
dispatch_queue_t thumbnailSetupQueue = dispatch_queue_create("com.App.SetupTimelineThumbnails", NULL);
dispatch_async(cellSetupQueue, ^{
NSManagedObjectContext *newMoc = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *coordinator = [NSManagedObjectContext contextForCurrentThread].persistentStoreCoordinator;
[newMoc setPersistentStoreCoordinator:coordinator];
NSNotificationCenter *notify = [NSNotificationCenter defaultCenter];
[notify addObserver:self
selector:#selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:newMoc];
Media *media = [localEntry.media anyObject];
UIImage *image = [media getThumbnail];
NSLog(#"image: %#", image);
[[NSNotificationCenter defaultCenter] removeObserver:self];
});
dispatch_release(cellSetupQueue);
Then
-(UIImage *)getThumbnail {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%#-%#.jpg",
self.mediaID,
THUMBNAIL_FILENAME]];
UIImage *thumbnail = [UIImage imageWithContentsOfFile:fullPath];
NSLog(#"correct size thumbnail: %#", correctSizeThumbnail);
return correctSizeThumbnail;
}
The NSLog in getThumbnailWithSave returns as a UIImage, the other NSLog returns as nil.
I had this problem explained to be a long time ago and I think this is how I fixed it.
Calling getThumbnail needs to be called back on the main thread.
So adding something such as:
UIImage *image;
dispatch_async(dispatch_get_main_queue(), ^{
image = [media getThumbnail];
});
or
UIImage *image = [media performSelectorOnMainThread:#selector(getThumbnail) withObject: nil, waitUntilDone:NO];
Again this is off the top of my head but I'm pretty sure this is how I went about it.

MPMoviePlayerController generate thumbnail of local video file and store it

I'm making an app that downloads movies from the server and stores them localy in the NSDocumentDirectory.
This works fine.
I want to add a thumbnail generated from each movie in front of the name in each cell.
My problem:
How can I generate a thumbnail from a movie after it is downloaded (so instantly, without having to play the movie first)? I want to store the thumbnails with the same name of the movie as a jpg in the NSDocumentDirectory.
My guess
-download movie and store it in NSDocumentDirectory (works)
-somehow load the movie in the MPMoviePlayerController's memory (don't know how)
-when loaded in memory, generate thumbnail with thumbnailImageAtTime (MPMovieTimeOptionNearestKeyFrame) (should work)
-store it (should work)
If anyone could help me...
Thanks
#import <MediaPlayer/MediaPlayer.h>
-(UIImage*)getFirstFrameFromVideoFile:(NSString*)sourceFilePath {
NSURL *videoURL = [NSURL fileURLWithPath:sourceFilePath];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
//Player autoplays audio on init
[player stop];
[player release];
return thumbnail;
}
Other tasks you know already.
Yes, using MPMoviePlayer works... but you must be sure that you do not have another movie player playing elsewhere in your app (even the UIWebView plug-in...) or you will get in trouble.
I do this way:
UIImage *thumbnail = nil;
NSURL *url = [NSURL fileURLWithPath:pathname];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform = YES;
NSError *error = nil;
CMTime time = CMTimeMake(3, 1); // 3/1 = 3 second(s)
CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:nil error:&error];
if (error != nil)
NSLog(#"%#: %#", self, error);
thumbnail = [[UIImage alloc] initWithCGImage:imgRef];
CGImageRelease(imgRef);
Hope this might help
This is the code I use which should generate the thumbnail
(added a big uiimageview for testing, works when I load a local image in it)
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"snijtechniekendir/videos"];
path = [path stringByAppendingPathComponent:[videos objectAtIndex:indexPath.row]];
NSURL *videoURL = [NSURL fileURLWithPath:path];
NSLog(#"video url: %#", videoURL);
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:1 timeOption:MPMovieTimeOptionNearestKeyFrame];
UIImageView *cellimage = [[UIImageView alloc] initWithFrame:CGRectMake(2, 2 , 400, 400)];
[cell.contentView addSubview:cellimage];
NSData *imgData = UIImagePNGRepresentation(thumbnail);
NSLog(#"lenght of video thumb: %#", [imgData length]);
[self.view addSubview:cellimage];
[cellimage setImage:thumbnail];
This is the log for one video file
video url: file://localhost/Users/Home/Library/Application%20Support/iPhone%20Simulator/5.1/Applications/78C165BB-75A9-46A2-A257-469F8652A665/Documents/snijtechniekendir/videos/snijtechniek%2520brunoise.mp4
lenght of video thumb: (null)

Upload pictures to my app

I´m designing a new app for an iPad. This app will work with a barcode scanner, and when it scans a code, it will show an image asociated.
I was thinking to build that asociating de barcode to an image name for example:
- Barcode 09090909 will show 09090909.png picture
- Barcode 19191919 will show 19191919.png picture
....
I think that there is no problem with that, but the problem comes when I need to add new barcode/pictures to the app. How can I send a new picture to my App? I see that when you develop on XCode and build you App, all the data goes into de App.
Any help or clue? thanks in advance
You can simple load them on the fly from your server, but then a network connection is required. To load them async from an server you can use this code:
dispatch_queue_t image_queue = dispatch_queue_create("com.company.app.imageQueue", NULL);
dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_async(image_queue, ^{
NSString *URLString = #"http://example.com/images/19191919.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(main_queue, ^{
[imageView setImage:image];
});
});
If you want you can also save the image to the cache dir (using the document dir is not recommended because it will collide with Apples iOS Data Storage Guidelines) and check before downloading an image twice, then the code will look like this:
NSString *fileName = #"19191919.png";
NSString *URLBaseString = #"http://example.com/images/";
NSString *URLString = [URLBaseString stringByAppendingString:fileName];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
NSString *dataPath = [cachePath stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ( [fileManager fileExistsAtPath:dataPath] )
{
UIImage *image = [UIImage imageWithContentsOfFile:dataPath];
[imageView setImage:image];
}
else
{
dispatch_async(image_queue, ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString];
UIImage *image = [UIImage imageWithData:imageData];
[UIImagePNGRepresentation(image) writeToFile:dataPath atomically:YES];
dispatch_async(main_queue, ^{
[imageView setImage:image];
});
});
}
This code has not been tested, but should work. Note that I'm relying on ARC to manage memory.

Getting Image from URL Objective C

I'm trying to get an image from an URL and it doesn't seem to be working for me. Can someone point me in the right direction?
Here is my code:
NSURL *url = [NSURL URLWithString:#"http://myurl/mypic.jpg"];
NSString *newIMAGE = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding error:nil];
cell.image = [UIImage imageNamed:newIMAGE];
When I debug the newIMAGE string is nil so something isn't working there.
What you want is to get the image data, then initialize a UIImage using that data:
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://myurl/mypic.jpg"]];
cell.image = [UIImage imageWithData: imageData];
[imageData release];
As requested, here's an asynchronous version:
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://myurl/mypic.jpg"]];
if ( data == nil )
return;
dispatch_async(dispatch_get_main_queue(), ^{
// WARNING: is the cell still using the same data by this point??
cell.image = [UIImage imageWithData: data];
});
[data release];
});
Ok there's a couple of things wrong here:
The conversion from URL (url) to NSString (newImage) is incorrect, what the code actually does there is try to load the contents of "http://myurl/mypic.jpg" into the NSString.
The -imageNamed method takes a string that is a path of a local file, not a URL as an argument.
You need to use an NSData object as an intermediary, like in this example:
http://blogs.oreilly.com/digitalmedia/2008/02/creating-an-uiimage-from-a-url.html
the accepted answer asynchronous version worked very slow in my code. an approach using NSOperation worked light years faster. the code provided by Joe Masilotti --> objective - C : Loading image from URL? (and pasted below):
-(void) someMethod {
// set placeholder image
UIImage* memberPhoto = [UIImage imageNamed:#"place_holder_image.png"];
// retrieve image for cell in using NSOperation
NSURL *url = [NSURL URLWithString:group.photo_link[indexPath.row]];
[self loadImage:url];
}
- (void)loadImage:(NSURL *)imageURL
{
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:#selector(requestRemoteImage:)
object:imageURL];
[queue addOperation:operation];
}
- (void)requestRemoteImage:(NSURL *)imageURL
{
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
UIImage *image = [[UIImage alloc] initWithData:imageData];
[self performSelectorOnMainThread:#selector(placeImageInUI:) withObject:image waitUntilDone:YES];
}
- (void)placeImageInUI:(UIImage *)image
{
[self.memberPhotoImage setImage:image];
}
In Swift 3 and 4
let theURL = URL(string:"https://exampleURL.com")
let imagedData = NSData(contentsOf: theURL!)!
let theImage = UIImage(data: imagedData as Data)
cell.theImageView.image = theImage
This will be done in the main thread.
And to perform the same in asynchronous/background thread
DispatchQueue.main.async(){
let theURL = URL(string:"https://exampleURL.com")
let imagedData = NSData(contentsOf: theURL!)!
let theImage = UIImage(data: imagedData as Data)
}
cell.theImageView.image = theImage
Updating upon Jim dovey answer,[data release] is no longer required because in the updated apple guidelines. Memory management is done automatically by ARC (Automatic counting reference) ,
Here is the updated asynchronous call,
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"your_URL"]];
if ( data == nil )
return;
dispatch_async(dispatch_get_main_queue(), ^{
self.your_UIimage.image = [UIImage imageWithData: data];
});
});