I used the code
-(IBAction)TakePhoto {
picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:nil];
[self performSegueWithIdentifier:#"CropImage" sender:sender];
}
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
//obtaining saving path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"latest_photo.png"];
//extracting image from the picker and saving it
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
NSData *webData = UIImagePNGRepresentation(editedImage);
[webData writeToFile:imagePath atomically:YES];
}
}
- (void)imagePickerControllerDidCancel :(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"CropImage"])
{
CropImageViewController *cropImageViewController = segue.destinationViewController;
cropImageViewController.theImage = yourImage;
// Similar to [segue.destinationViewController setTheImage:yourImage];
}
}
I have a problem here using the storyboard. I have multiple view controllers in the storyboard. I have the camera button (which the user can take the photo in app) on the first view controller. However I want to pass the data of the photo that the user took in the first view controller to another view controller automatically so that the user can crop it and then save it into a "directory or something"(did not decide yet).
update
I am having now four errors currently saying
http://tinypic.com/view.php?pic=15q6y3b&s=5
Click the image it will be bigger
Actually, you don't have to pass the photo directly to the next view since you had already saved it. You can simply read back the image from the same file in the target view controller. (This method is better if the view controllers are not close to one another.)
+ (UIImage *)readImageFromFile:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"latest_photo.png"];
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
return [UIImage imageWithData:imageData];
}
UPDATED: You can also pass the photo using property though.
In your target view controller (I will name it CropImageViewController), in .h,
#property (nonatomic, retain) UIImage *theImage;
In the "getPhoto" view controller, on top of the page,
#import "CropImageViewController.h"
In imagePickerController,
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
...
// This line should be
[self performSegueWithIdentifier:#"CropImage" sender:self];
}
In prepareForSegue method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"CropImage"])
{
CropImageViewController *cropImageViewController = segue.destinationViewController;
cropImageViewController.theImage = yourImage;
// Similar to [segue.destinationViewController setTheImage:yourImage];
}
}
Make sure you set a name, e.g. "CropImage", for the segue identifier in storyboard.
Related
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.
My app lets the user select the photo from camera roll or take the photo, the app saves the photo locally and then goes to the next view controller and loads the image that was just saved and displayed on an image view.
This is the code that I used to get the image the user wanted and sent it to my send picture method.
UIImage *image = info[UIImagePickerControllerEditedImage];
[self saveImage:image];
[picker dismissViewControllerAnimated:NO completion:NULL];
[self performSegueWithIdentifier:#"switch" sender:nil];
Which is this:
-(void)saveImage: (UIImage*)image{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"test.png"];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
printf("image saved");
}
That code ran because it printed the image was saved. The app goes to the next view and this is how I set up my viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
//[imageViewPreview setImage:self.secondImage];
//imageViewPreview.image = self.secondImage;
}
I commented out both ways that I've tried but neither of those works. This is how I was trying to get my secondImage to load:
-(UIImage* )secondImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"test.png"];
UIImage* image = [UIImage imageWithContentsOfFile:path];
printf("image loaded");
return image;
}
what is wrong here?
You should do this much simpler. In your second view controller add a public UIImage property. Then import the second controller into the first one. Then in prepareForSegue set it the image like this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"switch"]) {
ClassOfDEstinationController *destinationController = segue.destinationViewController;
destinationController.image = image;
}
}
This question already has answers here:
Send image to server as binary data
(2 answers)
Closed 9 years ago.
I want to upload image from UIImagePickerController.
I want to post my image to server from my iPad library.
I am not able to send the image to server. Any other options to do this?
I am doing this:
-(void)method_OpenImagePickerLibrary{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image=[info objectForKey:UIImagePickerControllerEditedImage];
SelectPickerimageView.image=image;
NSData *imageData = UIImagePNGRepresentation(image);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// Here is the file path for the image
filepath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"imagename.png"]];
[imageData writeToFile:filepath options:NSDataWritingAtomic error:nil];
[self dismissModalViewControllerAnimated:YES];
}
-(void)MethodUploadImage{
NSString *ftpUrl=#"ftp://yourftp Url";
NSString *strPortNumber=#"port Number";
NSString *strurlUpload=[NSString stringWithFormat:#"%#:%#",ftpUrl,strPortNumber];
NSString *getfilePath = filepath;
SCRFTPRequest *ftpRequest = [[SCRFTPRequest alloc] initWithURL:[NSURL URLWithString:strurlUpload] toUploadFile:getfilePath];
ftpRequest.username = #"Username";
ftpRequest.password = #"password";
ftpRequest.delegate = self;
/*
ftpRequest.didFinishSelector = #selector(uploadFinished:);
ftpRequest.didFailSelector = #selector(uploadFailed:);
ftpRequest.willStartSelector = #selector(uploadWillStart:);
ftpRequest.didChangeStatusSelector = #selector(requestStatusChanged:);
ftpRequest.bytesWrittenSelector = #selector(uploadBytesWritten:);*/
[ftpRequest startRequest];
}
These commented lines are giving me errors
Error 1: Undeclared selector
Error 2: Property
didFinishSelector,didFailSelector,willStartSelector,didChangeStatusSelector,bytesWrittenSelector
not found on SCRFtprequest delegate
Any idea or suggestion would be highly welcome.
Try using AFNetworking. It will surely make your life much easier.
I am trying to make my application open the camera app to take a save pictures.
from my application i am launching the camera application to take a picture with the following code:
-(IBAction)TakePhoto:(id)sender {
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:NULL];
[picker release];
//save image??:
//UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:NULL];
}
My problem is that once the button is pressed, the camera comes out and allows me to take a picture. Once the picture is take, the image is shown and i have the option to "retake" or "use". My issue is that if i click "use" the image is not saved to the camera roll. Is there a possibility to save the image and eventually change the "use" button to say "save"?
Thank you for you help!
The photo isn't being saved because you never actually added the code to save the image to the didFinishPickingMediaWithInfo: delegate method. All you have to do is add the line that you commented out in TakePhoto: to this function and you will be able to save the photo to the camera roll. E.x:
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, NULL);
[self dismissViewControllerAnimated:YES completion:NULL];
}
static NSDateFormatter* dateFormatter;
- (NSString*) generateNameWithExtension: (NSString*) extension
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyyMMddHHmmssSSS";
});
NSDate* now = [NSDate date];
NSString* string = [dateFormatter stringFromDate:now];
string = [NSString stringWithFormat:#"%#.%#",string,extension];
return string;
}
- (NSString*) saveImage: (UIImage*) image WithExtension: (NSString*) extension
{
extension = [extension lowercaseString];
NSData* data;
if ([extension isEqualToString:#"png"])
{
data = UIImagePNGRepresentation(image);
}else if ([extension isEqualToString:#"jpg"]||[extension isEqualToString:#"jpeg"])
{
data = UIImageJPEGRepresentation(image, 1.0);
}else{
NSLog(#"Error save local image, Extension: (%#) is not recognized, use (PNG/JPG)",extension);
return nil;
}
NSString* imageName = [self generateNameWithExtension:extension];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *finalPath = [documents stringByAppendingPathComponent:imageName];
[data writeToFile:finalPath options:NSAtomicWrite error:nil];
return finalPath;
}
This code save image in folder you app. You can later use it: [UIImage imageWithContentsOfFile:finalPath]
Hello I have an app that takes pictures but doesn't save. I know how to save the image to the Photo Album but I need the image to go to the app's directory and will not show up in the Photos gallery. I already have searched and I failed to look for a working one. I also need that image to be in my UIImageView when I open my app. Here are my codes:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UIImagePickerController *picker;
UIImagePickerController *picker2;
UIImage *image;
IBOutlet UIImageView *imageView;
}
-(IBAction)TakePhoto;
-(IBAction)ChooseExisting;
- (IBAction)btnSave:(id)sender;
- (IBAction)btnLoad:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)TakePhoto{
picker = [[UIImagePickerController alloc]init];
picker.delegate=self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:NULL];
// [picker release];
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImage.png"] ];
image = [UIImage imageWithContentsOfFile:path];
return image;
}
-(IBAction)ChooseExisting{
picker2 = [[UIImagePickerController alloc]init];
picker2.delegate=self;
[picker2 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker2 animated:YES completion:NULL];
// [picker release];
}
- (IBAction)btnSave:(id)sender {
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImage.png"]];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSLog(#"saved");
}
}
- (IBAction)btnLoad:(id)sender {
[self loadImage];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)viewDidLoad
{
[self loadImage];
[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.
}
#end
The Save and loadImage methods don't work :(. No idea why but I don't have any errors.
Your image saving/loading code seems correct.
Check if your IBActions are properly connected in IB.
And change:
- (IBAction)btnLoad:(id)sender
{
[self loadImage];
}
to:
- (IBAction)btnLoad:(id)sender
{
[self loadImage];
[imageView setImage:image];
}
Your original code seems to load the image but it doesn't show it anywhere.
EDIT:
You can always check if the image is saved to documents directory.
With the device connected open the organizer window in XCode.
Select your device, then select applications. Choose the application
you're interested in and you should see the file-tree related to that
app. Is your image file listed in the Documents folder?
Check in documents directory for image. Your calling [self loadImage]; but loadImage return UIImage which your not using anywhere. You can attach data to picker like the following.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"MyImage.png"];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
[picker2 addAttachmentData:myData mimeType:#"image/png" fileName:#"MyImage"];