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];
Related
Where to save image path i am uploading image for the gallery and need to pass the image path as a parameter
- (IBAction)chooseFileBtn:(id)sender {
// For picking image from gallery
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// output image
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
//self.profileImageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:nil];
}
Get the path of the image chosen from library using the following code in using Image Picker ViewController:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
NSString *imageName = [imagePath lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"localFilePath.%#",localFilePath);
}
For uploading this path to server as a parameter you can create a multipart/form-data request as in (POST multipart/form-data with Objective-C)
I hope it solves your issue.Happy coding!
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];
}
I have been trying to solve this issue since days. I have an app where the user selects an image than the selected image is saved to the disk and later loaded into a UIImageView, however this does not work, no matter what I try. i have made a small app just to test this, and it does not work there either. The imageView stays blank. Here is my code:
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)button:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.allowsEditing = NO;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
[self saveImage:selectedImage];
self.imageView.image = [self loadImage];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)saveImage: (UIImage*)image
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
#"image.png" ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
#"image.png" ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
#end
What am I doing wrong?
You just need to add the delegate of the UIImagePickerController so that following code solve you problem.
- (IBAction)button:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.allowsEditing = NO;
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
Now, In .h file use following code.
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
#property(nonatomic,weak)IBOutlet UIImageView *imageView;
#end
- (void)xuanquButtonClicked:(JohnButtonLong*)button
{
_picker = [[UIImagePickerController alloc] init];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
JLActionManager * manager = [JLActionManager sharedInstance];
[manager showAndHideHUDWithTitle:nil detailText:#"亲,您的相册无法打开" inView:self.view];
return;
}
_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
_picker.allowsEditing = YES;
_picker.delegate = self;
[self presentViewController:_picker animated:YES completion:^{
}];
}
#pragma mark - UIIMagePickerController delegate Methods
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:^{
}];
// 如果没有选取 使用默认头像
_strHeadPic = #"";
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
}];
// 选取了某个头像
UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
_img_touxiang.image = image;
//压缩图像
image = [self OriginImage:image scaleToSize:CGSizeMake(160, 160)];
NSData * img_data = UIImageJPEGRepresentation(image, 0.5);
//进行base64编码
NSData * data = [GTMBase64 encodeData:img_data];
_strHeadPic = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
// 压缩成指定大小
-(UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size{
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();// 是当前的context出对战
// 返回新的改变大小后的图片
return scaledImage;
}
UnitMyInfo * myInfo = GetMyInfo;
[_img_touxiang setImageWithURL:[NSURL URLWithString:BaseImgURL(myInfo.umi_URL)] placeholderImage:[UIImage imageNamed:#"default_headImg.jpg"]];
// First You have to get Url from Image then set url On SDWebImages.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editingInfo
{
[picker dismissModalViewControllerAnimated:YES];
NSURL *imagePath = [editingInfo objectForKey:#"UIImagePickerControllerReferenceURL"];
NSString *imageName = [imagePath lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"localFilePath.%#",localFilePath);
}
//Set Image On SDWebView.
[imageView setImageWithURL:[NSURL URLWithString:localFilePath] placeholderImage:[UIImage imageNamed:#"default_headImg.jpg"]];
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