如何在应用程序中存储图像(来自图库/相机)以便以后调用它?

时间:2014-05-20 16:51:47

标签: ios uiimageview nsstring uiimagepickercontroller

我确实已经弄明白了一次,但我做的方式并不太好,我开始遇到无法回答的问题......所以我又回到了基础。

在我的应用中,我有2个视图控制器(spViewController& secondViewController

on spViewController我有2 buttons 1带我去相机,另一个带我去相机滚动,然后在选择了图像后,它会使用{secondViewController移动到Unwinding Segue {1}}所有这一切都很好。当视图加载(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

如果您有任何想要查看更多代码,请告诉我们:)

提前感谢您的帮助

编辑:添加了所有代码

2 个答案:

答案 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];
 }

希望这会有所帮助

答案 1 :(得分: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];