UIImagePickerController - Save and Retrieve photo from Apps Document Directory - iphone

This is driving me crazy!
I'm successfully saving a photo to my applications document directory from both the camera and if I choose an existing one from the camera roll. The code to do this is as follows. Note I know this part is working because in the simulator I can browse to the apps Documents folder and see the file being saved.
Example "save" code:
//Note: code above snipped to keep this part of the question short
case 1:
{
// select from library
NSLog(#"select from camera roll");
if([util_ isPhotoLibraryAvailable])
{
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
if([util_ canUserPickPhotosFromPhotoLibrary])
{
[mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
}
controller.mediaTypes = mediaTypes;
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
}
} break;
//code below snipped out
And once the image is taken or selected:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSLog(#"picker returned successfully");
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(__bridge NSString *)kUTTypeImage])
{
UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *resizedImage = [util_ createThumbnailForImage:originalImage thumbnailSize:[util_ determineIPhoneScreenSize]];
NSData *imageData = UIImagePNGRepresentation(resizedImage);
NSString* imageName = #"MyImage.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:fullPathToFile atomically:NO];
NSLog(#"fullPathToFile %#", fullPathToFile);
// this outputs the following path in the debugger
// fullPathToFile /Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/47B01A4C-C54F-45C4-91A3-C4D7FF9F95CA/Documents/MyImage.png
// rest snipped out - at this point I see the image in the simulators/app/Documents directory
Now - the part that is NOT working (fetching and displaying the photo):
// code above snipped out (we're in tableView:cellForRowAtIndexPath)
imageButton_ = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 200, 200)];
NSString* imageName = [contentArray_ objectAtIndex:indexPath.row];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
SString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
UIImage *image = [UIImage imageNamed:fullPathToFile];
[imageButton_ setImage:image forState:UIControlStateNormal];
[cell addSubview:imageButton_];
NSLog(#"fullPathToFile: %#", fullPathToFile);
// this outputs the following path in the debugger
// fullPathToFile: /Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/47B01A4C-C54F-45C4-91A3-C4D7FF9F95CA/Documents/MyImage.png
return cell;
}
So, I get an empty button with no image displayed in the cell. I have also substituted the button for a UIImageView and still no luck...

Your problem is here:
UIImage *image = [UIImage imageNamed:fullPathToFile];
UIImage imageNamed: is only for images in the bundle. It doesn't work for images in the documents directory.
Try imageWithContentsOfFile: instead.

Related

Play recorded video using UIImagePickerController

I am creating an app which will record a video using UIImagePickerController and I am saving the recorded video in documents directory and trying to play back the video on click of USE (want to show the full first frame of recorded video along with play button in the middle like the native application of iPhone).
I am able to record the video and save it into document directory but unable to create the frame and playback.
I tried to move on new class where I can play the recorded video but gets crashed on click of USE button.
Here is my code
-(void)btnRecord_Press
{
BOOL canRecordVideo;
canRecordVideo = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
if (canRecordVideo)
{
UIImagePickerController *videoRecorder = [[UIImagePickerController alloc]init];
videoRecorder.sourceType = UIImagePickerControllerSourceTypeCamera;
videoRecorder.delegate=self;
videoRecorder.showsCameraControls = TRUE;
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(SELF CONTAINS %#)",#"movie"]];
BOOL movieOuputPossible = (videoMediaTypesOnly!=nil);
if (movieOuputPossible)
{
videoRecorder.mediaTypes = videoMediaTypesOnly;
[self presentViewController:videoRecorder animated:YES completion:nil];
}
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [documentsDirectory stringByAppendingFormat:#"/vid1.mp4"];
BOOL success = [videoData writeToFile:tempPath atomically:NO];
[self dismissViewControllerAnimated:NO completion:nil];
PlayMovie *play = [[PlayMovie alloc]initWithNibName:#"PlayMovie" bundle:Nil];
[self.navigationController pushViewController:play animated:YES];
}
Any help would be appreciable.
Thanks
I did this using this code.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
[self dismissViewControllerAnimated:NO completion:nil];
[self Play];
}
-(void)Play
{
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [documentsDirectory stringByAppendingFormat:#"/vid1.mp4"];
BOOL success = [videoData writeToFile:tempPath atomically:NO];
player = [[MPMoviePlayerController alloc]initWithContentURL:videoURL];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(btnDone_Press) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
self._player.shouldAutoplay = NO;
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
screenSize = [[UIScreen mainScreen]bounds].size;
if (screenSize.height >480.0f)
{
player.view.frame = CGRectMake(0, 0, 320, 548);
}
else
{
player.view.frame = CGRectMake(0, 0, 320, 460);
}
}
[self.view addSubview:player.view];
self._player.scalingMode = MPMovieScalingModeAspectFit;
self._player.fullscreen = YES;
[self._player play];
}

Image is not being shown when using UIImage imageWithData:NSData dataWithContentsOfFile

The below code is not displaying the image which is downloaded from online and written into my application documents directory.
i have checked inside the iphone's simulator documents directory , the downloaded file is exist.
but the image is not displayed.
When trying to add a resources image using UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"]; , the uiimageview displays the image.bu the image which is downloaded from online and stored inside the app directory is not displaying the image.
Pls let me know and thanks
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:theFileName];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath ){
//--------------
UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"];
imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)] autorelease];
[imageView1 setBackgroundColor:[UIColor grayColor]];
imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[cell addSubview:imageView1];
}
try this ,this is perfectly working for me:
- (void)viewDidLoad
{
  [super viewDidLoad];
NSURL *url1 = [NSURL URLWithString:#"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *workSpacePath = [documentsDirectory1 stringByAppendingPathComponent:#"savedImage.png"];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath )
{
imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(20,20,20,20)];
[imageView1 setBackgroundColor:[UIColor grayColor]];
imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubview:imageView1];
}
}
Instead of first converting the file to NSData, you can use
[UIImage imageWithContentsOfFile:filePath]
directly to load a image with given path.

Saving and Retrieving Image Makes App Slow

I save picture from UIImagePicker this way:
Save picture in file and then I save path to the fail in NSUserDefaults and then in another class I retrieve the picture by this saved path.
Code:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
ideaImage.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
[picker dismissModalViewControllerAnimated:YES];
}
-(void)saveIdea_alt
{
[self performSelector: #selector(saveIdea) withObject:nil afterDelay:0.1];
}
-(void)saveIdea
{
UIImage *ideaPhoto = ideaImage.image;
NSData *imageData = UIImagePNGRepresentation(ideaPhoto);
NSString* imageName = #"MyImage.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:fullPathToFile atomically:NO];
NSArray *arrayKeys = [[NSArray alloc]initWithObjects:#"ideaName",#"ideaCost",#"ideaNote", #"ideaImage", nil];
NSArray *arrayObjects = [[NSArray alloc]initWithObjects:ideaName.text,ideaCost.text,ideaNote.text,fullPathToFile , nil];
NSDictionary *dictionary = [[NSDictionary alloc]initWithObjects:arrayObjects forKeys:arrayKeys];
NSMutableArray *ideasArray = [[NSMutableArray alloc]initWithArray:[[NSUserDefaults standardUserDefaults]objectForKey:#"ideasArray"]];
[ideasArray addObject:dictionary];
[[NSUserDefaults standardUserDefaults]setObject:ideasArray forKey:#"ideasArray"];
[self dismissModalViewControllerAnimated:YES];
}
However, after that my app becomes slow and it saves and loads images slowly. What I do wrong ?
Thanks !
One interesting optimization to look at is not saving it into NSUserDefaults, and using Core Data.
There are a lot of reasons for this, but one important one is that when you want to add and remove things from NSUserDefaults, the app has to load all of NSUserDefaults into memory just go retrieve one key.

How to Display photos from NSDocumentDirectory

I'm developing this application on an iPad.
These codes for a 'Browse' button allows the user to view the photos from the iPad's gallery.
Code:
- (IBAction) BrowsePhoto:(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
[popover setPopoverContentSize:CGSizeMake(320,320)];
[popover presentPopoverFromRect:CGRectMake(200,200,-100,-100) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popoverController = popover;
[imagePickerController release];
}
When a photo is selected, it will be stored into the application using NSDocumentDirectory.
Code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
[self.popoverController dismissPopoverAnimated:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:#"SavedImage.png"];
UIImage *image = imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
Now i have to include a 'Display' button on the first screen.
When tapped on the button, it will show a new view (modal view controller) and displays all the photos in thumbnails/tableview from the NSDocumentDirectory.
When a photo is selected, it will be deleted from the NSDocumentDirectory.
How can i do this?
To Delete any file in NSDocumentDirectory in iPhone, U can use this code,
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath2 = [NSString stringWithFormat:#"%#/%#", docDirectory,#"SavedImage.png"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL exist =[fileManager fileExistsAtPath:filePath2];
if(exist)
[fileManager removeItemAtPath:filePath2 error:NULL];

Trying to save images in ipad app bundle from photo library

-(IBAction)saveImage{
NSMutableArray *dictWords= [[NSMutableArray alloc]initWithObjects:#"TIGER",#"CAT", #"ROSE", #"ELEPHANT",#"MOUSE IS LOOKING FOR THE CHEESE",#"KITE",#"CAR",#"AEROPLANE",#"MANGO",#"FRUITS ARE FALLING FROM THE TREE",#"MOUNTAIN",#"BIRDS ARE FLYING",#"IGLOO",#"THIS HOUSE IS BUILT OF WOODS",#"BANANA",#"RAINBOW",#"TRAIN",#"DADDY DRINKS JUICE",#"UMBRELLA",#"GOAT",#"CAT JUMPS HIGH",#"DOG RUNS FAST",#"BUS",#"GIRL IS CRYING",#"STARS",#"DOLPHIN",#"BOYS ARE PLAYING FOOTBALL",#"GLASS IS FULL OF WATER",#"SHIP",#"SNOWFALL",#"GHOST",#"RABBIT",#"WATERMELON",#"SPIDERMAN",#"DINOSAUR",#"MICKEY MOUSE",#"MONKEY IS SITTING ON A TREE",#"PEACOCK",#"LIGHTNING",#"HEN LAYS EGGS",nil];
NSString *path=[[NSBundle mainBundle] pathForResource:[youSaid text] ofType:#"png" inDirectory:#"Image"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i=0 ; i<[assets count]; i++) {
if (i<[dictWords count]) {
[dict setObject:[[[assets objectAtIndex:i] defaultRepresentation] url] forKey:[NSString stringWithFormat:#"%#",[dictWords objectAtIndex:i]]];
NSLog(#"diccount:%d",[dict count]);
}
}
NSURL *imageurl = [dict objectForKey:[youSaid text]];
//NSLog(#"text:%#",[youSaid text]);
//Getting asset from url
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
//Setting asset image to image view according to the image url
[imageview setImage:[UIImage imageWithCGImage:iref]];
youSaid.text = [NSString stringWithFormat:#"%#",imageurl];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Error, cant get image - %#",[myerror localizedDescription]);
};
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageurl resultBlock:resultblock failureBlock:failureblock];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", youSaid.text]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
}
#end
This is the following code i wrote but i am not able to save images.i am only able to sane an image known as NULL.png .please suggest the changes to save all the pics in my library to bundle.
Thanks,
Christy
Sample Code
- (void) openPhotoLibrary {
NSLog(#"openPhotolibrary");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
if (self.picker != nil) {
NSLog(#"releasing self.picker...");
[self.picker release];
}
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//self.picker.allowsImageEditing = YES;
[self.picker presentModalViewController:self.picker animated:YES];
self.picker.delegate = self;
[[[CCDirector sharedDirector] openGLView] addSubview:self.picker.view];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)currentPicker {
NSLog(#"imagePickerControllerDidCancel");
// hide the self.picker if user cancels picking an image.
[currentPicker dismissModalViewControllerAnimated:YES];
self.picker.view.hidden = YES;
[self.picker.view removeFromSuperview];
}
- (void)imagePickerController:(UIImagePickerController *)currentPicker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self saveImage:image withImageName:#"myPhoto"];
}
//saving an image
- (void)saveImage:(UIImage*)image withImageName:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
}
This code its working for me try it may be its helps you
-(IBAction)PhotoLibraryButtonClicked:(id)sender{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
}
else{
[self displaysorceError];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//[self.popoverrcontroller dismissPopoverAnimated:true];
//[popoverrcontroller release];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// UIImage *rote = [image rotateInDegrees:219.0f];
img.image = image;
if(newMedia)
UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//not available vidio
}
}
-(IBAction)saveImageIn:(id)sender{
NSData *imageData = UIImagePNGRepresentation(img.image);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#" %d.png",img.image]];
[fileMan createFileAtPath:fullPathToFile contents:imageData attributes:nil];
UIAlertView *alt = [[UIAlertView alloc]
initWithTitle:#"Thank You"
message:#"Image Save In Directory"
delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alt show];
[alt release];
}
thank you..:)Neet