after picking the image how save images locally in ios - ios

when i capture the image i need to save images one by one in table view like below image .is need use nsuser defaults or use core data?
and after picking the image how to add to Array

You can save image in NSUserDefaults as follows,
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
if(!self.phto_arr_)
{
self.phto_arr_ = [[NSMutableArray alloc] init];
}
[self.phto_arr_ addObject: chosenImage];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self.phto_arr_];
[[NSUserDefaults standardUserDefaults] setObject: encodedObject forKey:#"images"];
[[NSUserDefaults standardUserDefaults] synchronize];
[picker dismissViewControllerAnimated:YES completion:NULL];
}

Yes, you can save the images in the document directory and keep the image file names in an array after that retrieve that images from doc. dir. just like this
// For error information
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/YOUR_IMG_FOLDER"];
if (![fileMgr fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
//Get the current date and time and set as image name
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd_HH-mm-ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSString *gmtTime = [dateFormatter stringFromDate:now];
NSLog(#"The Current Time is :%#", gmtTime);
NSData *imageData = UIImageJPEGRepresentation(_postImage, 0.5); // _postImage is your image file and you can use JPEG representation or PNG as your wish
int imgSize = imageData.length;
////NSLog(#"SIZE OF IMAGE: %.2f Kb", (float)imgSize/1024);
NSString *imgfileName = [NSString stringWithFormat:#"%#%#", gmtTime, #".jpg"];
// File we want to create in the documents directory
NSString *imgfilePath= [dataPath stringByAppendingPathComponent:imgfileName];
// Write the file
[imageData writeToFile:imgfilePath atomically:YES];
**// Keep your Image file name into an mutable array here OR you can saved the array in a UserDefaults**
Then retrieve from doc. dir. from iterate the array.
//Get image file from sand box using file name and file path
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"YOUR_IMG_FOLDER"];
stringPath = [stringPath stringByAppendingPathComponent:imgFile]; // imgFile to get from your array, where you saved those image file names
UIImage *image = [UIImage imageWithContentsOfFile:stringPath];
Thank you...happy coding.

Try below this code:
suppose you want to image name also display use this code,
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
chosenImage = info[UIImagePickerControllerOriginalImage];
chosenImage = [UIImage unrotateImage:chosenImage];
addGalleryImageview.image = chosenImage;
isCameraOn = YES;
NSString* fileName = [NSString stringWithFormat:#"gallery%#",[Utils getDateString]];
imageNamelbl.text = fileName;
[picker dismissViewControllerAnimated:YES completion:NULL];}
- (UIImage*)unrotateImage:(UIImage*)image{
CGSize size = image.size;
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0,0,size.width ,size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;}

Related

save custom camera capture image iOS Xcode

I am new to iPhone, I want to save image into the album & I want that image path.
I did this already.
Now, I want a custom name for image & store image with that name.
I used below code but I am not getting any image into the album.
Can anybody guide me where am I wrong ?
#pragma mark - Image Picker Controller delegate methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
// Todo to use custom name comment this line.
//UIImageWriteToSavedPhotosAlbum(self.imageView.image,nil,nil,nil);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
});
}
You can Store Image with Custom name like this :
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
//save image in Document Derectory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Get Path : %#",documentsDirectory);
//create Folder if Not Exist
NSError *error = nil;
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
NSString *customePhotoName=#"MyPhotoName";
NSString* path= [dataPath stringByAppendingString:[NSString stringWithFormat:#"/%#.png",customePhotoName]];
NSData* imageData = UIImagePNGRepresentation(chosenImage);
[imageData writeToFile:path atomically:YES];
NSLog(#"Save Image Path : %#",path);
In one of my project I did this:
let directory = "yourDirectoryName"
let fileName = "file.png"
let directoryPath = NSHomeDirectory() + "/Library/Caches/\(directory)"
do {
try NSFileManager.defaultManager().createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil)
UIImagePNGRepresentation(image)?.writeToFile(directoryPath+fileName), atomically: true)
} catch let error as NSError {}
Code works in Swift 2.3. I hope, this is what you want.
Verify if NSData and UIImage objects are proper, set "atomically" as YES, check out the below code I use:
//Save your image with a completion selector
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
//Completion selector
- (void) image: (UIImage *) image
didFinishSavingWithError: (NSError *) error
contextInfo: (void *) contextInfo
{
if(error)
{
NSLog(#"save error :%#", [error localizedDescription]);
}
else if (!error)
{
PHAsset *asset = [self fetchImageAsset];
}
}
//Fetch image based on create date or whatever naming system you follow
- (nullable PHAsset *)fetchImageAsset
{
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
PHAsset *lastAsset = [fetchResult lastObject];
return lastAsset;
}

upload multiple images to ftp server

I am currently working IOS application which can be used to upload multiple image to ftp server. I am using GoldRaccoon class file. I have selected 5 images, but it only uploads the last image.
- (void)zcImagePickerController:(ZCImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(NSArray *)info {
[self dismissPickerView];
NSString *fullPath;
for (NSDictionary *imageDic in info) {
UIImageView *imageView = [[UIImageView alloc] initWithImage:[imageDic objectForKey:UIImagePickerControllerOriginalImage]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[arrImageView addObject:imageView];
UIImage *image1 = [imageDic objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData * imageData1 = UIImageJPEGRepresentation(image1,100); //convert image into .png format.
NSFileManager * fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray * paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString * documentsDirectory = [paths1 objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg",image1]]; //add our image to the path
// NSString *str=[NSString stringWithFormat:#"%#.jpg",image1];
[fileManager createFileAtPath:fullPath contents:imageData1 attributes:nil]; //finally save the image
[arrvalue addObject:fullPath];
NSURL *imageURL = [imageDic valueForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibraryAssetForURLResultBlock resultblock =^(ALAsset *myasset)
{
ALAssetRepresentation *representation = [myasset defaultRepresentation];
NSString *fileName = [representation filename];
// Send WebService
// [arrName addObject:fileName];
[self sendImage:fileName :fullPath];
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init] ;
[assetslibrary assetForURL:imageURL resultBlock:resultblock failureBlock:nil];
}
}

How to Save Image to Application Folder from UIImagePickerController?

I've a question in mind that driving me crazy. I've searched a lot to solve it, but all the answers that I found were old and not helped.
I'm currently working on application with that uses UIImagePickerControllerDelegate and with didFinishPickingMediaWithInfo I want to save the selected image to application folder.
Until now I'm able to select the image with this;
- (IBAction)btnPressed:(UIButton *)sender
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
imgPicker.delegate = self;
imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imgPicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage];
imgPicker.allowsEditing = NO;
[self presentViewController:imgPicker animated:YES completion:nil];
}
}
but couldn't save it to application using didFinishPickingMediaWithInfo;
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *) kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//Assigning the selected image to imageView to see on UI side.
imageViewerImage.image = image;
}
}
I wonder what should be the part after this point.
I appreciate any help that you can provide.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:NULL];
UIImage* image;
if([[info valueForKey:#"UIImagePickerControllerMediaType"] isEqualToString:#"public.image"])
{
image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"New Folder"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *fileName = [stringPath stringByAppendingFormat:#"/image.jpg"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[data writeToFile:fileName atomically:YES];
}
}
Try this code. It may helps you. :)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
imgViewProfile.image = info[UIImagePickerControllerEditedImage];
[picker dismissViewControllerAnimated:YES completion:^{ }];
// ------ Now save this image to document directory by getting its path
}
Save an UIImage to the to Documentsfolder like this:
UIImage* myUIImage = ...
NSData *pngData = UIImagePNGRepresentation(myUIImage);
//NSData *pngData = UIImageJPEGRepresentation(myUIImage,0.5); //alternative comressed jpg instead of png
NSString *filePath = [[self buildDocumentsPath] stringByAppendingPathComponent:#"pictureName.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
Get the path of the documents as a string:
- (NSString *)buildDocumentsPath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return documentsPath;
}
Just save the image in your app document directory :
// first find the path in which to save the image :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *baseDir = [paths objectAtIndex:0];
// then save image as JPEG
NSString* filename = [baseDir stringByAppendingPathComponent:#"filename.jpg"];
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];
// or PNG
NSString* filename = [baseDir stringByAppendingPathComponent:#"filename.png"];
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
//In Your - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo . Write this code
NSData *pngData = UIImagePNGRepresentation(image);
//This pulls out PNG data of the image you've captured. From here, you can write it to a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
I did that in my project:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage * imageDone = [info objectForKey:#"UIImagePickerControllerEditedImage"];
[self saveImage:imageDone];
[self.popover dismissPopoverAnimated:YES];
}
-(void)saveImage:(UIImage*)image{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString * imgpath = [documentsDirectory stringByAppendingFormat:#"/media/img/"];
long x = arc4random() % 10000;
NSString * namePic = [NSString stringWithFormat:#"%lld%ld-photo.jpg", self.idToLoad.longLongValue, x];
NSString * stringName = [NSString stringWithFormat:#"%#%#", imgpath, namePic];
[UIImageJPEGRepresentation(image, 0.3) writeToFile:stringName atomically:YES];
}

iOS UIImagePNGRepresentation crash due to "Memory Pressure"

I have UIImagePicker and UICollectionView in my view controller. I'am taking pictures and on 4th picture (it is also new line in collection view) application crashes due to "Memory Pressure". UIImagePicker delegate:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Do picture get here
NSError *error;
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(image);
NSNumber *imageNumber = [NSNumber numberWithInteger:[databaseManagementService selectTaskPictures].count];
NSString *imageName = [[imageNameDefault stringByAppendingString:[NSString stringWithFormat:objectFormat, imageNumber]] stringByAppendingString:extensionPNG];
// Do picture save to documents directory here
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:savedImagePath atomically:NO];
// Do UIImagePicker dismiss here
[picker dismissViewControllerAnimated:YES completion:nil];
// Do picture details save to database here
TaskManagerTaskPicture *taskPicture = [[TaskManagerTaskPicture alloc] init];
taskPicture.filename = imageName;
taskPicture.id = imageNumber;
taskPicture.title = imageName;
taskPicture.pictureID = self.taskObject.id;
taskPicture.taskID = self.taskObject.id;
taskPicture.locationID = self.taskObject.location.id;
[databaseManagementService insertTaskPictureObject:taskPicture andError:&error];
// Do task picture update here
// Do task object SELECT here
self.taskObject = [databaseManagementService selectTaskWithID:self.taskObject.id];
// Do task picture objects retreive from task object here
self.taskPictureObjects = [self.taskObject.taskPicture allObjects];
// Do collection data reload here
[self.taskPicturesCollectionView reloadData];
}
Until now I have been debuting and realized that trouble is dousing by line:
NSData *imageData = UIImagePNGRepresentation(image);
Does anyone have any idea how to fix this issue?
Can you explain better the flow of your app?
However try implementing this code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Do picture get here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSError *error;
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(image);
NSNumber *imageNumber = [NSNumber numberWithInteger:[databaseManagementService selectTaskPictures].count];
NSString *imageName = [[imageNameDefault stringByAppendingString:[NSString stringWithFormat:objectFormat, imageNumber]] stringByAppendingString:extensionPNG];
// Do picture save to documents directory here
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:savedImagePath atomically:YES];
dispatch_async(dispatch_get_main_queue(), ^{
// Do UIImagePicker dismiss here
[picker dismissViewControllerAnimated:YES completion:nil];
// Do picture details save to database here
TaskManagerTaskPicture *taskPicture = [[TaskManagerTaskPicture alloc] init];
taskPicture.filename = imageName;
taskPicture.id = imageNumber;
taskPicture.title = imageName;
taskPicture.pictureID = self.taskObject.id;
taskPicture.taskID = self.taskObject.id;
taskPicture.locationID = self.taskObject.location.id;
[databaseManagementService insertTaskPictureObject:taskPicture andError:&error];
// Do task picture update here
// Do task object SELECT here
self.taskObject = [databaseManagementService selectTaskWithID:self.taskObject.id];
// Do task picture objects retreive from task object here
self.taskPictureObjects = [self.taskObject.taskPicture allObjects];
// Do collection data reload here
[self.taskPicturesCollectionView reloadData];
});
});
}

how to set image name which we are saving in document directory

i am getting image from gallery now that image is getting displayed in application but same time i want to save that image in document directory
for that i am using below code
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage : (UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
selectImage.image = image;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"test.png"] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
[picker dismissModalViewControllerAnimated:YES];
}
now my question is you can see that i gave name as test.png but i want to set name of actual image. so every time user select different image and different name get stored
so how can i set actual name of image in path
plz help thank you :)
you can use following code to get new name every time to store your image
NSError *error = nil;
Get document directory Path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Grab the content Directory, all the files at location
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error];
Now get count of number of resources, and create new file name by adding 1 to current Count
NSString *newFileName = [NSString stringWithFormat:#"Test_%d.png",[contents count]+1];
You can use the below two lines to get the image name....may be it will use full for you..
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
NSString *imageName = [imagePath lastPathComponent];
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
NSString *originalImg = [imagePath lastPathComponent];
}

Resources