How to save a new-token photo in IOS - ios

I'm now struggling with UIImagePicker.
I've read the document but it seems not to mention how should I save a newly token photo, I mean save it into my own documents in my app.
In fact, there is a "photo" attribute in one of my entity in core data,
so, the "photo" should just be a NSString to save the real photo's file path, right?
But how to save that photo and get its correct file path?
I just know little about NSFilePath or something like that, hope someone to teach me a little bit.
Thanks a lot!

You may know how to present the image picker:
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[viewController presentModalViewController:picker animated:YES];
With the above the viewController implements the UIImagePickerControllerDelegate and make sure you implement this function:
- (void)imagePickerController:(UIImagePickerController *)returnedPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
and
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)returnedPicker
The first method is called when user has picked a photo. In this method you get the image using:
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
To write this to a file you can make it a JPEG or a PNG. If a JPEG you may do this:
[UIImageJPEGRepresentation(image, 1.0) writeToFile:filename atomically:YES];
You just need to set the filename.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [paths objectAtIndex:0];
NSString *filename = [docsDir stringByAppendingPathComponent:#"myFilename.jpg"];
To get the image back into a UIImage you do this:
NSData *data = [NSData dataWithContentsOfFile:filename;
if(data != nil)
UIImage *image = [UIImage imageWithData:data];

Related

How to pick the image name and image from iPhone photo library in iOS

I'm doing a pick a images from iPhone photo library or in other way from camera roll. I've done that without any problem. But I need to retrieve the picking the image name from the library. but I cant able to pick the image name from gallery. My requirement is I want to pick the image and image name from photo gallery and send the chat wall.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image =[[UIImage alloc] init];
image =[info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
//Here I am able to get the image path like this: assets-library://asset/asset.JPG?id=9F983DBA-EC35-42B8-8773-B597CF782EDD&ext=JPG
imageName = [imagePath lastPathComponent];
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);
//here the imageName is showing like this “asset.jpg”..
}
else
{
NSLog(#"no image name found");
}
}
-(void)sendMessage:(NSString *)messageTxt {
str=#"Ryan";
mesText=messageTxt;
senderImgName=[UIImage imageNamed:imageName];
//here the imageName is showing like this = asset.jpg
//but senderImgName= null.
NSString *str1=imageName;
NSLog(#"sender image name is:%#",senderImgName);
imgData=[NSData dataWithData:UIImageJPEGRepresentation(senderImgName, 0)];
finalImagePath=[imgData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSLog(#"Final image path is:%#", finalImagePath);
}
Use the Photos framework and import Photos/Photos.h
#import "Photos/Photos.h"
In your imagePickerController function add the following to get the filename of the selected image from the Photo library:
NSURL *imagePath = [editingInfo objectForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[imagePath] options:nil];
NSString *filename = [[result firstObject] filename];
NSLog(#"[filename ] %#", filename );
The result is like this: [filename ] IMG_0012.JPG

How to upload images from gallery to a supporting files in iOS?

I am a newbie to iOS and I have given a task of creating a small app, which allows user to select image from the gallery and selected image gets displayed in the UIImage view and should get saved in images folder under supporting files.
Currently image gets saved under documents folder, using following block of code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
localFilePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
self.imageView.image = image;
[picker dismissModalViewControllerAnimated:YES];
How can I save selected image under image folder in supporting files?
Following is the folder structure in my project
The image can be able to save in the phone memory not in the images folder what you have, If you want to save the image with in your project you can able to save through core data or sqlite database but you cannot see the image in your images folder.
Am not sure why you need to show that on the images folder but its not possible i think according to my knowledge.
Based on your requirement which is given by you on comment I have edited my previous answer.
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail setSubject:#"find attachment"];
UIImage *selectedImage = "put your image from your image view/ selected gallery image"
NSData *myData = UIImagePNGRepresentation(selectedImage);
[mail addAttachmentData:myData mimeType:#"image/png" fileName:#"coolImage.png"];
// set email body
NSString *emailBody = #"My cool image is attached";
[mail setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mail animated:YES];
All the best

Simulator shows my image in UIImageView but it doesn't on my real iPhone

I have looked around for the answer but it the answers I have found say that real devices are case sensitive and I've looked over my code and cannot find any problems,
I have 2 view controllers, spViewController which is my root and I have secondViewController which is self explanatory, there is an UIImageView in both to display the same image, which was picked from the gallery using UIImagePickerController in the simulator and real iPhone the image DOES display on the spViewController's UIImageView but on the secondViewController in the simulator the UIImageView DOES display the image but on the real iPhone the image DOES NOT display
This code is in my secondViewController.m
{NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepathJPG = [docsPath stringByAppendingPathComponent:#"imagefile.jpg"];
UIImage *img = [UIImage imageWithContentsOfFile: filepathJPG];
if (img != nil) {
_imageView.image = img;
BOOL adjustToSmallSize = YES;
CGRect smallSize = (CGRect){0,0,100,100};
if (adjustToSmallSize) {
_imageView.bounds = smallSize;
}
}
I have done a few tests of my own, I've been playing around with the file names and the caps and spellings, if i change the spellings of anything the image fails to load in the simulator also, if i keep it as imagefile.jpg then it loads in the simulator but not the real phone, I've played around with the caps and nothing seems to change on my iPhone or the simulator
Are you sure imagefile.JPG is upper case JPG, or could be imagefile.jpg? Also check what filepathJPG string holds on run time when your imageView fails to load this image file.
check your image name if it is ok than
delete DerivedData at /Library/Developer/Xcode/DerivedData/
and runs once again in the device.
I just look back my old project and this is how I write the image to the fullpath and also get the image back from the same path:-
if (self.photoView.image)
{
//Image file name
NSString *filename = [NSString stringWithFormat:#"M%#.png", self.title];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullPath = [NSString stringWithFormat:#"%#/%#", docDir, filename];
//Write the Image to the path
NSData *imageData = UIImagePNGRepresentation(self.photoView.image);
[imageData writeToFile:fullPath atomically:FALSE];
//Get the image back from the same path
UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
}
I just realised that you forgot the / for the path. Please make sure that whenever you write or read the path, you have that. Can you try it out and let me know if it solves your problem?
To fix my problem i did the following
in my FVC.m
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *chosenImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
//it returns the edited image
NSString *mediaType = info[UIImagePickerControllerMediaType];
self.myImage = chosenImage;
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = info[UIImagePickerControllerOriginalImage];
_imageView.image = image;
if (_newMedia)
{
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
}
}
[self performSelector:#selector(myMethod:) withObject:picker afterDelay:0.5];
}
and then this in my SVC.m
- (void)viewDidLoad
{
[super viewDidLoad];
_imageView.image = self.myImage;
hope this helps people in future

Load image from photo library without a picker?

Here is what I need.
I need my users to be able to pick an image from the photo library, however, they should not need to have to repick it each time they use it. Instead, I would like to remember the photo's path to be able to load it in the future. Is this possible? If not, what are the alternatives? Is it possible to cache the photo to a local folder or place?
Thanks
You can't keep an reference to the picked image, so you need to, as you suggest your self, save a local copy of the image. You could use the UIImagePicker to let the user pick the image and then save it locally:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage* image = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(image);
//save the imageData to document dir. You could also save it to the cache...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *finalPath = [documents stringByAppendingPathComponent:#"myImageName.png"];
[imageData writeToFile:finalPath atomically:YES];
}

didFinishPickingMediaWithInfo get Image filename

I am trying to get the image filename from the camera. I have seen many, many posts about retrieving the filename using UIImagePickerControllerReferenceURL or UIImagePickerControllerMediaURL, but that only gets you a filename similar to: //asset/asset.JPG?id=D1D715A8-6956-49FF-AF07-CE60FE93AE32&ext=JPG. I believe this is because the image is not saved yet, thus a name like img0001.jpg in not available.
Does anyone know how to get the filename? I am as suing I need to do this after UIImageWriteToSavedPhotosAlbum, but I cannot seem to figure it out.
I have seen the question asked many times, but none seem to 'really' answer it, they just always give the filename from an image chosen from the picker not from the camera.
Thanks for any help
** UPDATE:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self.popoverController dismissPopoverAnimated:true];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
imageView.image = image;
if (newMedia)
{
UIImageWriteToSavedPhotosAlbum(image,
self,
#selector(image:finishedSavingWithError:contextInfo:),
nil);
NSURL *refURL = [info valueForKey:UIImagePickerControllerMediaURL];
// 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];
}
}
}
My code above, but when imageRep filename is logged it is null.

Resources