As I am very much new to iOS development, I am trying to add an uiimage from image gallery to an array. But when I try to use the array to add image to uiimageview it shows me an error
[UIImage stringByDeletingPathExtension]: unrecognized selector sent to
instance 0x7fefd3ea02f0.
choosen_Imgae = info[ UIImagePickerControllerOriginalImage];
//
// choosen_Imgae = [self resizeImage:choosen_Image];
NSLog(#"chosen image %#",choosen_Imgae);
[picker dismissViewControllerAnimated:YES completion:NULL];
NSData *dataImage = [[NSData alloc] init];
dataImage = UIImagePNGRepresentation(choosen_Imgae);
if (dataImage != nil) {
[image_Arr insertObject:choosen_Imgae atIndex:indexxpath.row];
NSLog(#"image array after adding object %#",image_Arr);
}
Brother simply you can add the image to array.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *choosen_Imgae=[info objectForKey:#"UIImagePickerControllerOriginalImage"];
[image_Arr addObject:image];
[picker dismissViewControllerAnimated:YES completion:nil];
}
If you use NSData in didFinishPickingMediaWithInfo,it is long process(image->NSData).When fetching image from array again you have to convert NSData into image.So you can directly save the image into array.
Also you don't need to use insertObject to array.
When fetch the image from array
for (int i=0; i<[image_Arr count]; i++)
{
UIImage *fetch_Image = [image_Arr objectATIndex:i];
imageView.image = fetch_Image;
}
Related
I am a newbie in iOS development. I am trying to send a clicked image by encoding it into base64 format using SOAP. I don't know how to do this.
This is my imagePickerController delegate:
// delegate method for picking images
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info valueForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(NSString*)kUTTypeImage])
{
UIImage *photoTaken = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//Save Photo to library only if it wasnt already saved i.e. its just been taken
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
{
UIImageWriteToSavedPhotosAlbum(photoTaken, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
NSData *data=[[NSData alloc] initWithData:UIImagePNGRepresentation(photoTaken)];
base64= [[NSString alloc]init];
base64 =[data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
}
}
// [picker dismissModalViewControllerAnimated:YES];
[picker dismissViewControllerAnimated:YES completion:NULL];
[picker release];
}
in didFinishPickingMediaWithInfo..
UIImage* chosenImage =info[UIImagePickerControllerEditedImage];
//encoding image to base64
imgData=[[NSData alloc] initWithData:UIImagePNGRepresentation(chosenImage)];
_base64=[[NSString alloc]init];
_base64=[imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
self.tempbase= _base64;
and calling tempbase in soap message
The image size will be huge. It can reduce your app performance hence decrase the image size first by resizing the image.
-(UIImage *) imageWithImage:(UIImage *) image scaledTOSize:(CGSize) newsize
{
UIGraphicsBeginImageContext(newsize);
[image drawInRect:CGRectMake(0, 0, newsize.width, newsize.height)];
UIImage *newImg=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImg;
}
Now convert this small sized UIImage into NSData
NSData *imgData=[[NSData alloc] initWithData:UIImagePNGRepresentation(image)];
Then convert NSData into base64 string using third party library -
base64.h
NSData+Base64.h
NSstring *imgString = [imgData base64EncodedString];
imgString = [imgString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Now send this string to your services.
Code:
UIGraphicsBeginImageContext(self.drawImage.frame.size);
[self.drawImage.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *imageView = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData* data = UIImageJPEGRepresentation(imageView, 1.0f);
[Base64 initialize];
NSString *strEncoded = [Base64 encode:data];
NOTE: drawImage is object of UIImageView and Import Base64.h class.
I'm not sure where I'm doing the mistake, that's why I'd like to paste here some block of codes in order to find out what went wrong.
I have some PNG images that have transparent background and with using the block of codes below I'm trying save the selected image to application folder and NSUserDefault. And then I'm trying to call that saved image from application folder and display on UIBarButtonItem.
The purpose of saving to NSUserDefault as well is for testing.
So,
This is how I'm selecting the image.
- (IBAction)btnPressed:(UIButton *)sender
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
imgPicker.delegate = self;
imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imgPicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage];
imgPicker.allowsEditing = NO;
[self presentViewController:imgPicker animated:YES completion:nil];
}
}
And with this I'm saving it to application using didFinishPickingMediaWithInfo;
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *) kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//I believe this has the problem.
NSData *pngData = UIImagePNGRepresentation(image);
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"AppImages"];;
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *fileName = [stringPath stringByAppendingPathComponent:#"logoImage.png"];
[pngData writeToFile:fileName atomically:YES];
NSUserDefaults *logoUserDef = [NSUserDefaults standardUserDefaults];
[logoUserDef setValue:pngData forKey:#"logoImageData"];
}
}
Note: I don't have problem for the images that doesn't have transparent background.
And lastly this is how I'm calling it from both Application and NSUserDefault.
Using both NSUserDefaults and AppDirectory to see if they're showing different result.
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"logoImageData"])
{
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
UIImage *testing = [UIImage imageWithData:[user valueForKey:#"logoImageData"]];
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:#"logoImage" ofType:#"png" inDirectory:documentsDirectory];
UIBarButtonItem *logoBarButton = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:#selector(logoTapped)];
logoBarButton.imageInsets = UIEdgeInsetsMake(9, 0, 9, 90);
logoBarButton.image = [logoBarButton.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[self.navigationItem setLeftBarButtonItems:#[logoBarButton]];
}
And method that returns UIImage from App Document.
-(UIImage *)loadImageWithFileName:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#/%#.%#", directoryPath, #"AppImages", fileName, [extension lowercaseString]]];
return result;
}
I don't know from where I'm doing wrong but as always, when I select image that has transparent background. It always convert its background to White. I need to save it as it is as transparent. I've searched a lot but couldn't find anything to solve this.
Any help is appreciated.
Solved the problem!
The block of codes that I posted with my question have nothing wrong. The problem was occurring from iTunes, when I synchronize images from my Mac to my iPhone iTunes convert them to JPEG and because of this images loses their transparency etc... and when I select images using my app, I was selecting them as JPEG without being aware and that's why I had these problems.
So I came up with a solution to have images via email. I just send them from my mac to iPhone with e-mail, and by this images didn't lose anything as a feature. After that when I used them in app as a right image, the program worked as it supposed to be.
You wrote
[logoUserDef setValue:pngData forKey:#"logoImageData"];
but I don't see where you synchronize. So add:
[logoUserDef synchronize];
I was able to preserve the transparency when saving an image to the Documents directory after using
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *img = [info valueForKey:UIImagePickerControllerOriginalImage];
[yourButton setImage:img forState:UIControlStateNormal];
NSData *pngData = UIImagePNGRepresentation(img);
//do something with pngData
}
The key is the UIImagePickerControllerOriginalImage instead of other options like UIImagePickerControllerEditedImage.
I have this code right here.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
NSData* imgData=UIImagePNGRepresentation(chosenImage);
[[NSUserDefaults standardUserDefaults] setObject:imgData forKey:#"image"];
[[NSUserDefaults standardUserDefaults]synchronize];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
and then in another view I have
-(void)showImage{
NSData* image=[[NSUserDefaults standardUserDefaults] objectForKey:#"image"];
UIImage* img=[UIImage imageWithData:image];
//now you can use that img image on any imageview
UIImageView *imageView = [[UIImageView alloc] initWithImage:img];
}
I'm trying nsuserdefaults to load the image in the second view, but no matter what I do it won't show in the UIImageView.
Please don't tell me to not use nsuserdefaults I have to use it
UIImageView *imageView = [[UIImageView alloc] initWithImage:img]
And obligatory, don't store images in NSUserDefaults
I am working on an application that needs its user to upload a photo for him, using iphone, how can i implement this : when click on the image in my personal information page, the gallery is opend to choose a photo. when the photo is chosen it must appear instead of the previous one (at first it is the default pic). Notice that, the path of this photo or the photo itself(i do not know) must be stored in the DataBase for the next login. Moreover, this photo must be transferred to the server in order to be shown on the website when the same user login on the web.
I did it using the following code, i can choose a photo but when i save the path i could not load the pic again. it is a white box !! there is no photo !!
-(void) pickPhoto
{
UIImagePickerController *picker ;
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
else
{
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
[self presentViewController:picker animated:YES completion:nil];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
if(!img)
img = [info objectForKey:UIImagePickerControllerOriginalImage];
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDirPath stringByAppendingPathComponent:#"myImage.png"];
NSLog (#"File Path = %#", filePath);
UIButton *btn = (UIButton *)[self.tableView viewWithTag:2013];
[btn setBackgroundImage:img forState:UIControlStateNormal];
database= [[connectToDB alloc] init];
[database setDelegate:self];
[database saveUserPic:filePath ForUser:user.userId];
[self dismissViewControllerAnimated:YES completion:nil];
}
now to load the pic :
UIImage *img;
if(pic != nil)
img=[UIImage imageWithContentsOfFile:pic];
else
img= [UIImage imageNamed:#"business_userL.png"];
Any Help will be appreciated.!
UIImagePickerControllerReferenceURL will return reference to local storage of your selected image.
NSURL* localUrl = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
Now you can save this url in your database.
To retrieve the image : display image from URL retrieved from ALAsset in iPhone
In my app, If user selects an image from camera roll to use as a compnay logo (added to a final pdf) it can take the attached file size from 8mb (with no image) to 29mb in some cases. This is a problem when user emails the file as its lager than most servers will allow for attachement sizes
- (IBAction)schemeLogoPressed:(id)sender {
LogCmd();
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
imagePicker.allowsEditing = NO;
[self.editController presentModalViewController:imagePicker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
DebugLog(#"info dict: %#", info);
[picker dismissModalViewControllerAnimated:YES];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.schemeLogo.backgroundColor = [UIColor whiteColor];
self.schemeLogo.image = image;
NSData *imageData1 = UIImagePNGRepresentation(image);
NSString *path1 = [ICUtils pathForDocument:#"schemeLogo.png"];
[imageData1 writeToFile:path1 atomically:NO];
Is there anything I can do to optimise the picked image size?
Change this line:
NSData *imageData1 = UIImagePNGRepresentation(image);
to:
NSData *imageData1 = UIImageJPEGRepresentation(image, 0.9f);
the second parameter (0.9 float) is the quality. Higher number, higher quality. from 0.0 to 1.0