2014-05-20 55 views
1

我確實已經弄清楚了一次,但是我做到這一點的方式工作得不好,而且我開始遇到無法解答的問題......所以我又回到了基礎知識。如何將圖像(來自圖庫/相機)存儲在應用程序中以稍後調用它?

在我的應用程序我有2個視圖控制器(spViewController & secondViewController

spViewController我有2 buttons 1帶我到照相機和其它帶我到相機膠捲,然後後的圖像已被選擇其移動到secondViewController使用Unwinding Segue所有這一切都很好。當視圖加載時(viewDidLoad)我想要選擇的圖像顯示在UIImageView準備使用的地方,我將要覆蓋圖像(此時疊加圖像無關)

這裏是我的代碼迄今爲止使用。如果需要,我願意更改所有代碼。

這裏是我的RootVC.h(spViewController)

#import <UIKit/UIKit.h> 
#import <MobileCoreServices/MobileCoreServices.h> 
#import "secondViewController.h" 
@interface spViewController : UIViewController 


<UIImagePickerControllerDelegate, 
UINavigationControllerDelegate> 

@property BOOL newMedia; 


@property (strong, nonatomic) IBOutlet UIImageView *imageView; 
@property (strong, nonatomic) spViewController *secondViewController; 
@property (strong, nonatomic) UIImageView *image; 
@property (strong, nonatomic) UIImage *myImage; 

- (IBAction)useCamera:(id)sender; 


- (IBAction)useCameraRoll:(id)sender; 


@end 

spViewController.m

#import "spViewController.h" 
#import "secondViewController.h" 

@interface spViewController() 

@end 

@implementation spViewController 

- (IBAction)backtohome:(UIStoryboardSegue *)unwindSegue 
{ 
} 

- (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)useCamera:(id)sender { 
     if ([UIImagePickerController isSourceTypeAvailable: 
      UIImagePickerControllerSourceTypeCamera]) 
     { 
      UIImagePickerController *imagePicker = 
      [[UIImagePickerController alloc] init]; 
      imagePicker.delegate = self; 
      imagePicker.sourceType = 
      UIImagePickerControllerSourceTypeCamera; 
      imagePicker.mediaTypes = @[(NSString *) kUTTypeImage]; 
      imagePicker.allowsEditing = YES; 
      [self presentViewController:imagePicker 
           animated:YES completion:nil]; 
      _newMedia = NO; 
     } 
    } 

- (IBAction)useCameraRoll:(id)sender { 

    if ([UIImagePickerController isSourceTypeAvailable: 
     UIImagePickerControllerSourceTypeSavedPhotosAlbum]) 
    { 
     UIImagePickerController *imagePicker = 
     [[UIImagePickerController alloc] init]; 
     imagePicker.delegate = self; 
     imagePicker.sourceType = 
     UIImagePickerControllerSourceTypePhotoLibrary; 
     imagePicker.mediaTypes = @[(NSString *) kUTTypeImage]; 
     imagePicker.allowsEditing = NO; 
     [self presentViewController:imagePicker 
          animated:YES completion:nil]; 
     _newMedia = NO; 
    } 
} 



//image picker delegate 
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage]; 
    self.myImage = chosenImage; //hear u are getting image from both camera or gallery 

    NSString *mediaType = info[UIImagePickerControllerMediaType]; 

    [self performSelector:@selector(myMethod:) withObject:info afterDelay:0.1]; 

    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) 
    { 

     UIImage *image = info[UIImagePickerControllerOriginalImage]; 

     _imageView.image = image; 
     if (_newMedia) 
     { 
      UIImageWriteToSavedPhotosAlbum(image,self, @selector(image:finishedSavingWithError:contextInfo:), nil); // uncomment this 
      if(imageData != nil) 
      { 
       /* 
       NSString *pngPath = @"/imagefolder/imagefrompicker.png"; 
       NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
       NSString *pngPath = [NSString stringWithFormat:@"%@%@",Dir,pngPath]; //path means ur destination contain's this format -> "/foldername/picname" pickname must be unique 
       if(![[NSFileManager defaultManager] fileExistsAtPath:[pngPath stringByDeletingLastPathComponent]]) 
       { 
        NSError *error; 
        [[NSFileManager defaultManager] createDirectoryAtPath:[pngPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error]; 
        if(error) 
        { 
         NSLog(@"error in creating dir"); 
        } 
       } 
       [imageData writeToFile:pngPath atomically:YES]; //saving to a file, use it later by using path 
       */ end if(imageData != nil) 
      } 

     } 

    } 
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) 
    { 

    } 
} 

-(void)myMethod:(NSDictionary *)info { 
    [self dismissViewControllerAnimated:YES completion:^{ 
     NSLog(@"Perform segue"); 
     [self performSegueWithIdentifier:@"Picture Unwind Segue" sender:self]; 
    }]; 
} 


-(void)image:(UIImage *)image 
finishedSavingWithError:(NSError *)error 
contextInfo:(void *)contextInfo 




{ 
    if (error) { 
     UIAlertView *alert = [[UIAlertView alloc] 
           initWithTitle: @"Save failed" 
           message: @"Failed to save image" 
           delegate: nil 
           cancelButtonTitle:@"OK" 
           otherButtonTitles:nil]; 
     [alert show]; 
    } 
} 
//cancel delegate 

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
{ 
    [self dismissViewControllerAnimated:YES completion:nil]; 
} 

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    if ([[segue identifier]isEqualToString:@"Picture Unwind Segue"]) { 
     secondViewController *destinationViewController = [segue destinationViewController]; 
     destinationViewController.myImage = self.myImage; //just set the image of secondViewController 
    } 
} 

@end 

seconViewController.h

#import <UIKit/UIKit.h> 
#import <MobileCoreServices/MobileCoreServices.h> 
#import "spViewController.h" 

@interface secondViewController : UIViewController 

<UIImagePickerControllerDelegate, 
UINavigationControllerDelegate> 


@property (strong, nonatomic) UIImage *myImage; //changed and synthesised 
@property (strong) UIImageView *imageView; //check what it this for 
@property (strong, nonatomic) IBOutlet UIImageView *imageView; //name changed and also see in story bord for correct binding to this outlet 

@end 

secondViewController.m

#import "secondViewController.h" 
#import "spViewController.h" 

@interface secondViewController() 

@end 

@implementation secondViewController 

@synthesize myImage; 


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _imageView.image = self.myImage; 
    //comment every thing  
    // NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    // NSString *pngPath = [NSString stringWithFormat:@"%@%@",Dir,InDestination->@/imagefolder/imagefrompicker.png]; //you know already where the image is InDestination->@"/foldername/picname" 

    // UIImage *img = [UIImage imageWithContentsOfFile:pngPath]; // get the saved image 
    // if (img != nil) { 

     // assigning 
    //  _imageView.image = img; //use the image 

     //size 
    //  BOOL adjustToSmallSize = YES; 
    //  CGRect smallSize = (CGRect){0,0,100,100}; 
    //  if (adjustToSmallSize) { 
    //   _imageView.bounds = smallSize; 
    //  } 
    // } 
    // else { 
    //  NSLog(@"Image hasn't been created"); 
    // } 

} 

@end 

如果你們想看到更多的代碼,請不要讓我知道:)

感謝您的幫助提前

編輯:添加所有代碼

+0

我編輯了代碼檢查它 –

+0

我更新了我的代碼,以顯示你已經做了什麼,如果我做錯了請幫助我有'NSString * pngPath = [NSString stringWithFormat:@「%@%@」 ,'Dir,InDestination - > @「/ imagefolder/imagefrompicker.png」];' 我得到「期望的標識符」,「和使用未聲明的標識符inDestination'」,並且在這一行上''NSString * pngPath = [NSString stringWithFormat:@「%@%@」,Dir,pngPath];' 在我的第一個VC中,我得到了「重新定義pngPath」 –

+0

我編輯了代碼並在我的答案中提出,檢查 –

回答

1

試試這個沒有 在確保spViewController.m

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
     UIImage *chosenImage = info[UIImagePickerControllerEditedImage]; 
     self.myImage = chosenImage; 

     NSString *mediaType = info[UIImagePickerControllerMediaType]; 

     [self performSelector:@selector(myMethod:) withObject:info afterDelay:0.1]; 

    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) 
    { 
     UIImage *image = info[UIImagePickerControllerOriginalImage]; 

     _imageView.image = image; 
     if (_newMedia) 
     { 
     // UIImageWriteToSavedPhotosAlbum(image,self, @selector(image:finishedSavingWithError:contextInfo:), nil); // change hear, u are saving to album, insted of this save to a folder in your app bundle and use it anywhere 
      NSData *imageData = UIImagePNGRepresentation(image); //get the data of image 
      if(imageData != nil) 
      { 
       NSString *DespngPath = @"/imagefolder/imagefrompicker"; 
       NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
       NSString *pngPath = [NSString stringWithFormat:@"%@%@",Dir,DespngPath]; //path means ur destination contain's this format -> "/foldername/picname" pickname must be unique 
       if(![[NSFileManager defaultManager] fileExistsAtPath:[pngPath stringByDeletingLastPathComponent]]) 
       { 
       NSError *error; 
       [[NSFileManager defaultManager] createDirectoryAtPath:[pngPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error]; 
       if(error) 
       { 
        NSLog(@"error in creating dir"); 
       } 
       } 
      [imageData writeToFile:pngPath atomically:YES]; //saving to a file, use it later by using path 
     } 
    } 
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) 
    { 

    } 
    } 

secondViewController.m

- (void)viewDidLoad 
    { 
     NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
     NSString *InDestination = @"/imagefolder/imagefrompicker"; 
     NSString *pngPath = [NSString stringWithFormat:@"%@%@",Dir,InDestination]; //you know already where the image is InDestination->@"/foldername/picname" 

     UIImage *img = [UIImage imageWithContentsOfFile:pngPath]; // get the saved image 
     if (img != nil) { 
     // assigning 
     _imageView.image = img; //use the image 

     //size 
     BOOL adjustToSmallSize = YES; 
     CGRect smallSize = (CGRect){0,0,100,100}; 
     if (adjustToSmallSize) { 
     _imageView.bounds = smallSize; 
     } 
    } 
    else { 
     NSLog(@"Image hasn't been created"); 
    } 
    [super viewDidLoad]; 
} 

希望這將有助於你

+0

有點混淆你的意思是在這個路徑中意味着你的目的地包含這種格式 - >「/文件夾名/圖片名」選擇名必須是唯一的,我只是選擇一個文件夾和圖像的名稱?例如:「image folder/imagefrompicker001.png」? 另外我得到一個錯誤,「使用未聲明的標識符」路徑「' –

+0

你可以直接選擇或指定一個圖像名稱,爲了更好的可讀性,我把那個 –

+0

@ C.爲什麼我編輯代碼,檢查它 –

0

我認爲你可以通過做一些比將圖像保存到磁盤更簡單的方式來實現這一點。 您可以簡單地將圖像作爲第一個控制器中的屬性,並將代表添加到第二個協議中。

在你的第二個控制器的.h文件中:

// outside of the @interface 
@protocol SecondControllerDelegate <NSObject> 
- (UIImage *)selectedImage; 
@end 

// Along with other properties 
@property (nonatomic, weak) id<SecondControllerDelegate> delegate; 

在你的第一個控制器,當你介紹它之前初始化你的第二控制器:

SecondController *controller = [[SecondController alloc] init]; 
//your initialization 
controller.delegate = self; 

在你的第一個控制器的.h文件中:

#import "SecondViewController.h" 
    @interface FirstViewController: UIViewController <SecondControllerDelegate> 

在您的第一個控制器的.m文件中:

- (UIImage *)selectedImage 
{ 
// return the selected image here that you should store in a property. 
} 

最後,在你的SecondViewController中。M檔,當你需要獲取圖像:

self.myImageView.image = [self.delegate selectedImage]; 
+0

恩,對不起,我真的不明白你的意思 –

+0

編輯我的答案更清楚。 – Champoul

+0

這沒有爲我工作,你想看到我的整個代碼,然後你可以看到我的工作原理? –

相關問題