uiimagepickercontroller - get the name of the image selected from photo library - iphone

I am trying to upload the image from my iPhone/iPod touch to my online repository, I have successfully picked the image from Photo Album but i am facing one problem i want to know the name of the image such as image1.jpg or some thing like that. How i would know the name of the picked image.

Instead of using the usual image picker method (UIImage*)[info valueForKey:UIImagePickerOriginalImage] which gives you the selected image as an instance of UIImage, you can use the AssetsLibrary.framework and export the actual source file (including format, name and all metadata). This also has the advantage of the original file format (png or jpg) being preserved.
#import <AssetsLibrary/AssetsLibrary.h>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self dismissPicker];
// try to get media resource (in case of a video)
NSURL *resourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
if(resourceURL) {
// it's a video: handle import
[self doSomethingWith:resourceURL];
} else {
// it's a photo
resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibrary *assetLibrary = [ALAssetsLibrary new];
[assetLibrary assetForURL:resourceURL
resultBlock:^(ALAsset *asset) {
// get data
ALAssetRepresentation *assetRep = [asset defaultRepresentation];
CGImageRef cgImg = [assetRep fullResolutionImage];
NSString *filename = [assetRep filename];
UIImage *img = [UIImage imageWithCGImage:cgImg];
NSData *data = UIImagePNGRepresentation(img);
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSURL *tempFileURL = [NSURL fileURLWithPath:[cacheDir stringByAppendingPathComponent:filename]];
BOOL result = [data writeToFile:tempFileURL.path atomically:YES];
if(result) {
// handle import
[self doSomethingWith:resourceURL];
// remove temp file
result = [[NSFileManager defaultManager] removeItemAtURL:tempFileURL error:nil];
if(!result) { NSLog(#"Error removing temp file %#", tempFileURL); }
}
}
failureBlock:^(NSError *error) {
NSLog(#"%#", error);
}];
return;
}
}

I guess knowing the exact image name would not be an issue rather getting a unique name for the picked image would solve your purpose so that you can upload the image on server and track it via its name. May be this can help you
NSMutableString *imageName = [[[NSMutableString alloc] initWithCapacity:0] autorelease];
CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
if (theUUID) {
[imageName appendString:NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, theUUID))];
CFRelease(theUUID);
}
[imageName appendString:#".png"];
After you pick the image from Picker you can generate a unique name and assign it to the Picked image.
Cheers

Related

Programmatically save image by specifying name in ios [duplicate]

How can I save an image (like using UIImageWriteToSavedPhotosAlbum() method) with a filename of my choice to the private/var folder?
Kenny, you had the answer! For illustration I always think code is more helpful.
//I do this in the didFinishPickingImage:(UIImage *)img method
NSData* imageData = UIImageJPEGRepresentation(img, 1.0);
//save to the default 100Apple(Camera Roll) folder.
[imageData writeToFile:#"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO];
UIImageWriteToSavedPhotosAlbum() is only used for saving to the photos camera roll. To save to a custom folder, you need to convert the UIImage into NSData with UIImageJPEGRepresentation() or UIImagePNGRepresentation(), then save this NSData to anywhere you like.
You can use below code, without use of ALAssetsLibrary...
NSString *fileName;
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera )
{
UIImageWriteToSavedPhotosAlbum(image,nil, nil, nil);
[self performSelector:#selector(GetImageName) withObject:nil afterDelay:0.5];
}
else
{
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[refURL] options:nil];
fileName = [[result firstObject] filename];
}
}];
-(void)GetImageName
{
NSString *str =#"";
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
str = [[fetchResult lastObject] filename];
}
fileName = str;
}

UIImagePickerController - Save and Retrieve photo from Apps Document Directory

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.

How to obtain the original file name of the image picked by UIImagePickerController?

I've implemented the delegate method and can get access to the picked UIImage, like this:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *pickedImage = [info valueForKey:UIImagePickerControllerOriginalImage];
I want to save it to a directory, but I need a file name. So rather than just picking a random file name it would make sense to pick the same file name as the image.
Is there a way to retrieve it from that info dictionary?
You could use the UIImagePickerControllerReferenceURL value of the info dictionary instead of the UIImagePickerControllerOriginalImage. This should give you the URL to the original media item.
This would return you a NSURL object which you then can use to build your new filename from.
Use ALA Assets library framework
Use the code below
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error )
{
[library assetForURL:assetURL resultBlock:^(ALAsset *asset )
{
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSLog(#"reference image filename picking from camera: %#", [imageRep filename]);
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:assetURL resultBlock:resultblock failureBlock:nil];
}
failureBlock:^(NSError *error )
{
NSLog(#"Error loading asset");
}];
}];
imageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
imageView.contentMode = UIViewContentModeScaleAspectFit;

How can i avoid Location service in AlAssetLibrary? Can i retrieve files using AlAssetLibrary without using Location Service?

i created a application to get images from iPhone photo Folder using ALAssetLibrary.
Can i retrieve files using AlAssetLibrary without using Location Service?
How can i avoid Location service in AlAssetLibrary?
Currently there is no way to access ALAssetLibrary without using location services. You have to use the, much more limited, UIImagePickerController to get around that problem.
The above answer is incorrect if you only need one image from the library. For example, if you are having the user choose a photo to upload. In this case you can get that single image with ALAssetLibrary, without needing Location permissions.
To do this, use a UIImagePickerController to select the picture; you just need the UIImagePickerControllerReferenceURL, which the UIImagePickerController provides.
This has the benefit of giving you access to an unmodified NSData object, which you can then upload.
This is helpful because re-encoding the image later using UIImagePNGRepresentation() or UIImageJPEGRepresentation() can double the size of your file!
To present the picker:
picker = [[UIImagePickerController alloc] init];
[picker setDelegate:self];
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker animated:YES completion:nil];
To get the image and/or data:
- (void)imagePickerController:(UIImagePickerController *)thePicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
NSURL *imageURL = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageURL
resultBlock:^(ALAsset *asset) {
// get your NSData, UIImage, or whatever here
ALAssetRepresentation *rep = [self defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullScreenImage]];
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];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
failureBlock:^(NSError *err) {
// Something went wrong; get the image the old-fashioned way
// (You'll need to re-encode the NSData if you ever upload the image)
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}];
}

UIImage Saving image with file name on the iPhone

How can I save an image (like using UIImageWriteToSavedPhotosAlbum() method) with a filename of my choice to the private/var folder?
Kenny, you had the answer! For illustration I always think code is more helpful.
//I do this in the didFinishPickingImage:(UIImage *)img method
NSData* imageData = UIImageJPEGRepresentation(img, 1.0);
//save to the default 100Apple(Camera Roll) folder.
[imageData writeToFile:#"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO];
UIImageWriteToSavedPhotosAlbum() is only used for saving to the photos camera roll. To save to a custom folder, you need to convert the UIImage into NSData with UIImageJPEGRepresentation() or UIImagePNGRepresentation(), then save this NSData to anywhere you like.
You can use below code, without use of ALAssetsLibrary...
NSString *fileName;
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera )
{
UIImageWriteToSavedPhotosAlbum(image,nil, nil, nil);
[self performSelector:#selector(GetImageName) withObject:nil afterDelay:0.5];
}
else
{
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[refURL] options:nil];
fileName = [[result firstObject] filename];
}
}];
-(void)GetImageName
{
NSString *str =#"";
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
str = [[fetchResult lastObject] filename];
}
fileName = str;
}