Get photo file with metadata from album photo - iphone

It is possible to retrieve photo file from the album photo with metadata (IPTC)?
I've tried UIImagePickerController to get UIImage and when I save it to a file, it doesn't contain any metadata information.
There is a way to get the original photo file with ALAsset library?

I found a solution with AssetsLibrary:
- (void)savePhoto:(NSURL*) url <br
{
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
NSString* originalFileName = [[asset defaultRepresentation] filename];
NSString *path = [applicationDocumentsDir stringByAppendingPathComponent:originalFileName];
ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
//NSLog(#"%#",data);
[data writeToFile:path atomically:YES];
} failureBlock:^(NSError *err) {
NSLog(#"Error: %#",[err localizedDescription]);
}];
}

Related

When we open pdf in iPhone then how to save this pdf in iphone

I am very new to iOS. I create PDF and load this PDF on UIWebView
now this time I want to save or download this PDF in iPhone when we tapped download button then all exits PDF supporter show like as open ibook ,open in chrome. This type of option show but when we tap any one then my application closed.
-(void)show_Button
{
NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docDirectories objectAtIndex:0];
NSString *filePAth = [docDirectory stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
docContr.delegate=self;
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
so how to save or download this pdf in Iphone please solve this problem....
I believe you can simple use the belo two line:
NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your_url"]];
[myFile writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
I hope this it will help you,
Saving the pdf into app
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"pdfname.pdf"];
NSError *writeError = nil;
[imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
if (writeError) {
NSLog(#"Error writing file: %#", writeError); }
Getting the pdf from the NSDocument Directory
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:&error];
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"pdf"])
{
NSString *pdfPath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:pdfPath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[arrayOfImages addObject:image];
}
}
}

Writing orignal image with exif to Document Directory folder from ALAsset object

I want to save alasset imagearray directly to document directory with EXIF
i tried PNG conversion, jpeg conversion nothing worked
It just creating new image either with jpg or png (loss of exif)
I have seen some time back to save NSData Directly to folder to preserve EXIF dont know how
I am getting metadata from ALAsset object result with
NSDictionary *metadata = [[result defaultRepresentation] metadata];
Another assets array with list of all images
ALAssetsGroupEnumerationResultsBlock assetEnumerator = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != NULL) {
[assets addObject:result];
;
NSLog(#"assets %i",[assets count]);
self.progressView.progress = (float)index / ([assets count]-1);
}
Saving images to document directory folder
-(void)saveImagesToDocumentDirectory{
NSLog(#"assets count %i",[assets count]);
for(int i=0;i<[assets count];i++)
{
currentImage = [UIImage imageWithCGImage:[[[assets objectAtIndex:i] defaultRepresentation] fullResolutionImage]];
[self saveImage:currentImage withImageName:[NSString stringWithFormat:#"Images %d",i]];
} }
- (void)saveImage:(UIImage*)image withImageName:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
// NSData *imageData = UIImageJPEGRepresentation(image,1.0);
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 *dataPath = [documentsDirectory stringByAppendingPathComponent:#"MyFolder"];
NSString *fullPath = [dataPath 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 is the method i am able to write all images in my document directory folder with exif remain intact, hope this will help other users
-(void)writingOutImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *documentdataPath = [documentsDirectory stringByAppendingPathComponent:#"MyFolder"];
NSLog(#"documentdataPath %#",documentdataPath);
for (int j=0; j<[assets count]; j++) {
ALAssetRepresentation *representation = [[assets objectAtIndex:j] defaultRepresentation];
NSString* filename = [documentdataPath stringByAppendingPathComponent:[representation filename]];
[[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil];
NSOutputStream *outPutStream = [NSOutputStream outputStreamToFileAtPath:filename append:YES];
[outPutStream open];
long long offset = 0;
long long bytesRead = 0;
NSError *error;
uint8_t * buffer = malloc(131072);
while (offset<[representation size] && [outPutStream hasSpaceAvailable]) {
bytesRead = [representation getBytes:buffer fromOffset:offset length:131072 error:&error];
[outPutStream write:buffer maxLength:bytesRead];
offset = offset+bytesRead;
}
[outPutStream close];
free(buffer);
}
}

Saving image persistently in within App - iOS

Trying to select image using photo picker and save that image internally in apps folder.
- (void) imagePickerController: (UIImagePickerController *) pickerdidFinishPickingMediaWithInfo: (NSDictionary *) info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToUse;
// Handle a still image picked from a photo album
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
== kCFCompareEqualTo) {
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToUse = editedImage;
} else {
imageToUse = originalImage;
}
// Do something with imageToUse
//save it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:#"%d", myUniqueID]];
NSString *imagePath = [imageName stringByAppendingPathComponent:#".png"];
NSData *webData = UIImagePNGRepresentation(editedImage);
NSError* error = nil;
bool success = [webData writeToFile:imagePath options:NULL error:&error];
if (success) {
// successfull save
imageCount++;
[[NSUserDefaults standardUserDefaults] setInteger:imageCount forKey:#"imageCount"];
NSLog(#"#Success save to: %#", imagePath);
}
else if (error) {
NSLog(#"Error:%#", error.localizedDescription);
}
}
...
}
What I can't figure out is that writeToFile::: returns false but no value is returned in error so I can't figure out whats going wrong. Any help would be greatly appreciated thanks
You're missing a "/". The line:
NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:#"%d", myUniqueID]];
should be:
NSString *imageName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d", myUniqueID]];
And the line that says:
NSString *imagePath = [imageName stringByAppendingPathComponent:#".png"];
should be:
NSString *imagePath = [imageName stringByAppendingPathExtension:#"png"];
Update:
And, shouldn't:
NSData *webData = UIImagePNGRepresentation(editedImage);
be the following?
NSData *webData = UIImagePNGRepresentation(imageToUse);

How save images in home directory?

I am making an application in which i have use Json parsing. With the help of json parsing i get photo url which is saved in string. To show images in my cell i use this code
NSString *strURL=[NSString stringWithFormat:#"%#", [list_photo objectAtIndex:indexPath.row]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: strURL]];
CGRect myImage =CGRectMake(13,5,50,50);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImage];
[imageView setImage:[UIImage imageWithData: imageData]];
[cell addSubview:imageView];
Now prblem is that when i go back or forword then i have wait for few second to come back on same view. Now i want that i when application is used first tme then i wait for that screen otherwise get images from home directory. How i save these image in my home directory? How access from home directory?
You can save an image in the default documents directory as follows using the imageData;
// Accessing the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"myImage.png"];
//Writing the image file
[imageData writeToFile:savedImagePath atomically:NO];
You can use this to write a file to your Documents Folder
+(BOOL) downloadFileFromURL:(NSString *) url withLocalName:(NSString*) localName
{
//Get the local file and it's size.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:localName];
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:finalPath error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
int localFileSize = [[fileAttributes objectForKey:NSFileSize] intValue];
//Prepare a request for the desired resource.
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"HEAD"];
//Send the request for just the HTTP header.
NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
//Check the response code
int status = 404;
if ([response respondsToSelector:#selector(statusCode)])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
status = [httpResponse statusCode];
}
if (status != 200)
{
//file not found
return NO;
}
else
{
//file found
}
//Get the expected file size of the downloaded file
int remoteFileSize = [response expectedContentLength];
//If the file isn't already downloaded, download it.
if (localFileSize != remoteFileSize || (localFileSize == 0))
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
return YES;
}
//here we may wish to check the dates or the file contents to ensure they are the same file.
//The file is already downloaded
return YES;
}
and this to read:
+(UIImage*) fileAtLocation:(NSString*) docLocation
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:docLocation];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
NSData *databuffer = [[NSFileManager defaultManager] contentsAtPath:finalPath];
UIImage *image = [UIImage imageWithData:databuffer];
return image;
}

iPhone Save Movie Clip - Doesn't work on 3GS

The following code works on iPad and iPhone/iPod 4, but will not work on 3G/3GS, meaning the movie clips won't save. The os on our test 3G/3GS devices is > 4.0.
-(void)processMovieClipSave:(NSConnection*)connection
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
SystemSoundID snapShot;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"tapsound" ofType:#"wav"]],&snapShot);
AudioServicesPlaySystemSound(snapShot);
NSData* data = [NSData dataWithContentsOfURL:moviePlayerController.contentURL];
NSString* path = nil;
NSString *paths = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
path = [paths stringByAppendingPathComponent:#"/src.mp4"];
[data writeToFile:path atomically:NO];
NSURL *clipURL = [NSURL URLWithString:path];
//NSLog(#"Save Clip URL: %#",[clipURL absoluteString]);
ALAssetsLibrary* library = [[[ALAssetsLibrary alloc]init]autorelease];
[library writeVideoAtPathToSavedPhotosAlbum:clipURL completionBlock:^(NSURL *assetURL, NSError *error)
{
NSMutableDictionary *dict = nil;
if (error)
{
dict = [[NSMutableDictionary alloc]init];
[dict setObject:error forKey:#"error"];
}
[self performSelectorOnMainThread:#selector(onMovieClipSaved:) withObject:dict waitUntilDone:NO];
if (dict)
[dict release];
}];
[pool release];
}