代码改变世界

Save Image to UserDefaults(用NSUserDefaults保存图片)

2017-03-15 20:58  supper_Ho  阅读(720)  评论(0编辑  收藏  举报

//save to Userdefaults
    
    NSData *imageData;
    // create NSData-object from image
    imageData = [NSKeyedArchiver archivedDataWithRootObject:yourUIImage];
    // save NSData-object to UserDefaults
    [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"image"];
    
    //load imag from Userdefaults
    NSData *imageData;
    imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"image"];
    
    if(imageData != nil)
    {
        yourUIImage = [NSKeyedUnarchiver unarchiveObjectWithData: imageData];
    }
    
    
    save
    
    //Save to PNG
    NSData *dataObj = UIImagePNGRepresentation(self);
    [dataObj writeToFile:path atomically:NO];
    
    //Save to JPG
    NSData *dataObj = UIImageJPEGRepresentation(self, 90);
    [dataObj writeToFile:path atomically:NO];
    
    
    Demo class:
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
    {
        if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
        {
            NSData *imageData;
            UIImage *theImage;
            imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"image"];
            if(imageData != nil)
            {
                    theImage = [NSKeyedUnarchiver unarchiveObjectWithData: imageData];    
            }    
        }
        return self;
    }
    
    - (IBAction)openPicker
    {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])    
        {
            UIImagePickerController *picker;
            picker = [[UIImagePickerController alloc]init];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;        
            picker.allowsImageEditing = YES;            
            picker.delegate = self;
            [self presentModalViewController:picker animated:YES];
        }
    }

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
    {

        [self useImage:image];    
        [[picker parentViewController] dismissModalViewControllerAnimated:YES];
    }
    
    -(void)useImage:(UIImage *)theImage
    {

        pickerImage.image = theImage;
        NSData *imageData;
        imageData = [NSKeyedArchiver archivedDataWithRootObject:theImage];
        [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"image"];
    }