How to copy image from device into sandbox of application? - ios

I need to copy image from the device into the sandbox of the app! Say in Library/Cache folder! How do I do it? I searched in the internet i didnt find the solution. Please help!
EDIT:
#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
ALAssetsLibrary *lib=[ALAssetsLibrary new];
for (int i=0; i<assets.count; i++) {
ALAsset *asset=assets[i];
FileOP *fileMgr=[[FileOP alloc]init];
NSString *baseDir=[fileMgr GetDocumentDirectory];
//STORING FILE INTO LOCAL
[lib assetForURL:asset.defaultRepresentation.url
resultBlock:^(ALAsset *asset){
ALAssetRepresentation *repr = [asset defaultRepresentation];
CGImageRef cgImg = [repr fullResolutionImage];
NSString *fname = repr.filename;
UIImage *img = [UIImage imageWithCGImage:cgImg];
NSData *data = UIImagePNGRepresentation(img);
[data writeToFile:[baseDir stringByAppendingPathComponent:fname]
atomically:YES];
//FOR LOCAL URL OF THE IMAGE
NSString *imageURL = [baseDir stringByAppendingPathComponent:fname];
NSLog(#"%# URL OF IMAGE ",imageURL);
[[ImageArray sharedImageArray]setImageUrl:imageURL atIndex:i];
//NSLog(#"%# is the shared array",[[ImageArray sharedImageArray] getImageUrlAtIndex:i];
}
failureBlock:^(NSError *error){
}];
}
NSLog(#"COPIED %lu FILE INTO LOCAL MEMORY",(unsigned long)assets.count);
//NEED TO STORE THE PATH OF THE SELECTED IMAGE FILES INTO SOME ARRAY HERE
}

You can do it like that :
In .h, implement the UIImagePickerControllerDelegate delegate :
#interface yourClass : NSObject <UIImagePickerControllerDelegate>
In .m, create a method fired when you click on a button. It will open your photo library and save the picked image into the cache folder :
- (IBAction)pickFromAlbum:(id)sender
{
UIImagePickerController *pickerController = [UIImagePickerController new];
pickerController.delegate = self;
pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:pickerController animated:YES completion:nil];
}
Then implement the delegate method :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Get image into a variable
UIImage *takenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
// Get the cache folder
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDir = [dirPaths objectAtIndex:0];
// Save image into cache folder
NSData *data;
data = [NSData dataWithData:UIImageJPEGRepresentation(takenImage, 1.0f)]; // 1.0f = quality 100%
[data writeToFile:[cacheDir stringByAppendingPathComponent:#"fileName.jpeg"] atomically:YES];
// Hide the picker
[picker dismissViewControllerAnimated:YES completion:nil];
}

Related

Setting Image from gallery in iOS

I select an image from gallery and display on UIImageView but when I click back button and again open push to the image view controller that image is empty.
What should I do to remain same image on UIImageView after logout also?
I have used this code:
- (void)viewDidLoad {
NSString *myGrrabedImage1=#"myGrrabedImage1.png";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1=[path objectAtIndex:0];
NSString *fullPathToFile1=[documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
NSData *data=[NSData dataWithContentsOfFile:fullPathToFile1];
[[self teacherImg]setImage:[UIImage imageWithData:data]];
[data writeToFile:fullPathToFile1 atomically:YES];
}
- (IBAction)selectImg:(id)sender {
pickerController = [[UIImagePickerController alloc]init];
pickerController.delegate = self;
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
UIImage * img = [info valueForKey:UIImagePickerControllerEditedImage];
teacherImg.image = img;
[self presentViewController:pickerController animated:YES completion:nil];
}
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
NSData *data=UIImagePNGRepresentation(teacherImg.image);
NSString *myGrrabedImage1=#"myGrrabedImage1.png";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1=[path objectAtIndex:0];
NSString *fullPathToFile=[documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
[data writeToFile:fullPathToFile atomically:YES];
imagePicker.allowsEditing = YES;
imagePicker.delegate = self;
[[self teacherImg]setImage:image];
[self dismissViewControllerAnimated:YES completion:nil];
}
In viewDidLoad() method you need to load image from doc. dir.
NSString *myGrrabedImage1 = #"myGrrabedImage1.png";
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1 = [path objectAtIndex:0];
NSString *fullPathToFile = [documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
Method 1:
NSData *imgData = [NSData dataWithContentsOfFile: fullPathToFile];
UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
Method 2:
UIIMage *image = [UIImage imageWithContentsOfFile: fullPathToFile];
[imgView setImage: image];
You should read the image data and set the ImageView image in the viewWillAppear method.
viewDidLoad is called only once, after the view has been loaded from the xib/storyboard
Try this way;
- (void)viewDidLoad {
NSString *myGrrabedImage1 = #"myGrrabedImage1.png";
NSArray *path =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1 = [path objectAtIndex:0];
NSString *pathFile = [documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
UIIMage *image = [UIImage imageWithContentsOfFile: pathFile];
[teacherImg setImage: image];
}
- (IBAction)selectImg:(id)sender {
pickerController = [[UIImagePickerController alloc]init];
pickerController.delegate = self;
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:pickerController animated:YES completion:nil];
}
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
UIImage * img = [info valueForKey:UIImagePickerControllerEditedImage];
teacherImg.image = img;
NSData *data=UIImagePNGRepresentation(teacherImg.image);
NSString *myGrrabedImage1=#"myGrrabedImage1.png";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory1=[path objectAtIndex:0];
NSString *fullPathToFile=[documentDirectory1 stringByAppendingPathComponent:myGrrabedImage1];
[data writeToFile:fullPathToFile atomically:YES];
[[self teacherImg]setImage:image];
[self dismissViewControllerAnimated:YES completion:nil];
}

copy gallery image to project files Objective-C

I am new in Objective-C and I want choose one image from a Gallery and I want get the name and the extension and copy that image to my project folder.
Use UIimagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if ([mediaTypeStr isEqualToString:#"photo"])
{
if ([info objectForKey:UIImagePickerControllerOriginalImage])
{
// images = [NSMutableArray arrayWithCapacity:[info count]];
_images = [[NSMutableArray alloc]init];
UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];;
img =[self scaleAndRotateImage:img];
[_images addObject:img];
// Save Photo to library only if it wasnt already saved i.e. its just been taken
[self.alAsstlibrary saveImage:img toAlbum:#"FOlder name" completion:^(NSURL *assetURL, NSError *error)
{
if (error!=nil)
{
//NSLog(#"Big error: %#", [error description]);
}
} failure:nil];
}
else
{
//NSLog(#"UIImagePickerControllerReferenceURL = %#", info);
}
}
[picker dismissViewControllerAnimated:YES completion:Nil];
}
write these in viewdidload or on the buttons click event as per your need..
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = NO;//by writing YES here you can edit image also..
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
imgview=[[UIImageView alloc]initWithFrame:CGRectMake(x+y, y, width, height)];
[imgview setTag:i];
imgview.contentMode = UIViewContentModeScaleAspectFill;
[imgview setClipsToBounds:YES];
[self.view addSubview:imgview];
write these in your .m file..
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//if you write picker.allowsEditing = YES; than write info[UIImagePickerControllerEditedImage] in BELOW line....
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
imgview.image = chosenImage;//set selected image in your imageview
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
i hope it helps..
To achieve this follow these steps.
Get the image
- (void) getPicture:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = (sender == myPic) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentModalViewController:picker animated:YES];
[picker release];
}
You will get the image in imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self save:image];
[picker dismissModalViewControllerAnimated:YES];
}
Save image in documents
-(void)save:(UIImage*)image
{
NSData *pngData = UIImagePNGRepresentation(image);
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
}
Get document path
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
Get the Image
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];

Save Imagedata in the imageview

In the app i made an image view that holds the Image chosen from the library of the phone or taken by the camera. But when I go back to the previous scene the image chosen is gone. I want it to be saved in the image view and have a clear button to remove it. The camera function works but the image doesn't stay in the image view.
The camera function:
.h file
#interface FMEImageView : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
IBOutlet UIImageView *ImageView;
UIImagePickerController *picker;
UIImage *image;
}
- (IBAction)Takephoto:(id)sender;
- (IBAction)Chosenphoto:(id)sender;
#end
.m file
- (IBAction)Takephoto:(id)sender{
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)Chosenphoto:(id)sender{
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker animated:YES completion:NULL];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
[ImageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:NULL];
}
I think, you will have to save images to the documents directory of your application.
Get image data.
NSData *imgData = UIImagePNGRepresentation(image);
Write it to documents directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"];//Choose name for the image.
[imgData writeToFile:filePath atomically:YES]; //Write the file
Get the data and display it on the imageView.
Again, get filePath.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"];//Name you have given
NSData *imgData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:imgData];
imageView.image = image;
It is better to make a function to get the path of documents directory.
I hope it helps.
You might be using new instance every time. use same instance once initialized.

Get image name from UIImageWriteToSavedPhotosAlbum in ios [duplicate]

This question already has answers here:
Getting image name of iphone photo library
(2 answers)
Closed 9 years ago.
I've searched how to get the name of the saved image takes from the camera, but i didn't find something simple.
this is my code :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error )
{
NSLog(#"IMAGE SAVED TO PHOTO ALBUM");
[library assetForURL:assetURL resultBlock:^(ALAsset *asset )
{
NSLog(#"we have our ALAsset!");
NSLog(#"%#", assetURL);
}
failureBlock:^(NSError *error )
{
NSLog(#"Error loading asset");
}];
}];
}
}
I you have the answer, i will happy to test it .
Thanks in advance.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *resourceURL;
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image =[[UIImage alloc] init];
image =[info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
NSString *imageName = [imagePath lastPathComponent];
resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
NSData *imageData;
NSString *extensionOFImage =[imageName substringFromIndex:[imageName rangeOfString:#"."].location+1 ];
if ([extensionOFImage isEqualToString:#"jpg"])
{
imageData = UIImagePNGRepresentation(image);
}
else
{
imageData = UIImageJPEGRepresentation(image, 1.0);
}
int imageSize=imageData.length/1024;
NSLog(#"imageSize--->%d", imageSize);
if (imageName!=nil) {
NSLog(#"imageName--->%#",imageName);
}
else
{
NSLog(#"no image name found");
}
}
If you are using ASSerts
-(void)assetPickerController:(WSAssetPickerController *)sender didFinishPickingMediaWithAssets:(NSArray *)assets
{
[self dismissViewControllerAnimated:YES completion:^{
if (assets.count < 1) return;
//self.pageControl.numberOfPages = assets.count;
int index = 0;
for (ALAsset *asset in assets) {
// NSString *imageName = [[asset defaultRepresentation] filename];
UIImage *image = [[UIImage alloc] initWithCGImage:asset.defaultRepresentation.fullScreenImage];
// (#"%#", [[asset defaultRepresentation] filename]);
NSData *imageData = UIImagePNGRepresentation(image);
int imageSize=imageData.length/1024;
(either)
NSURL *imagePath = [asset objectForKey:#"UIImagePickerControllerReferenceURL"];
// NSURL *imagePath = [NSURL URLWithString:[asset ob]];
NSString *imageName = [imagePath lastPathComponent];
(or)
NSLog(#"%#",[[asset defaultRepresentation] filename]);
index++;
}
}];
}
Try following code. I have used this in one of my previous project and its working for me :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
_selectedImage = info[UIImagePickerControllerEditedImage];
self.photoView.image = _selectedImage;
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSLog(#"[imageRep filename] : %#", [imageRep filename]);
};
// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
[picker dismissViewControllerAnimated:YES completion:NULL];
}

Saving image from camera to documents directory

I have the following code which launches the camera app and the user can select "use photo". However nothing happens.
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] == YES) {
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:imagePickerController animated:YES];
}
How I can I get an UIimage from this and save it to the photo album. Ideally I'd like to save this to the documents directory and know how to do that part. Thanks!
-(void) imagePickerController:(UIImagePickerController *)UIPicker didFinishPickingMediaWithInfo:(NSDictionary *) info
{
UIImage* originalImage = nil;
originalImage = [info objectForKey:UIImagePickerControllerEditedImage];
if(originalImage==nil)
{
originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
}
if(originalImage==nil)
{
originalImage = [info objectForKey:UIImagePickerControllerCropRect];
}
[addImageOutlet setImage:originalImage forState:UIControlStateNormal];
[self saveBackgroundImageInDocumentDirectory:originalImage];
[self dismissViewControllerAnimated:YES completion:nil];
}
Use this code:
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData * imageData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
[imageData writeToFile:savedImagePath atomically:NO];
[picker dismissViewControllerAnimated:YES completion:nil];
}
I think it will help you,
//you have to set the delegate which clicking the button of camera
imagePickerController.delegate = self;
//This Delegate method will call
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage* selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
NSString *path = [[self pathToPatientPhotoFolder] stringByAppendingPathComponent:[NSString stringWithFormat:#"imageName.png"]];
NSError * error11 = nil;
[post.getData writeToFile:path options:NSDataWritingAtomic error:&error11];
}
//This method is useful for the get the Documentry path
- (NSString *)pathToPatientPhotoFolder {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
NSString *myalbumpath = [documentsDirectory stringByAppendingPathComponent:#"MYAlbum"];
// Create the folder if necessary
BOOL isDir = NO;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (![fileManager fileExistsAtPath:myalbumpath
isDirectory:&isDir] && isDir == NO) {
[fileManager createDirectoryAtPath:myalbumpath
withIntermediateDirectories:NO
attributes:nil
error:nil];
}
return myalbumpath;
}
Enjoy the coding
addImageOutlet for what type of object

Resources