Convert UIImage to NSData and save with core data

前端 未结 8 788
不知归路
不知归路 2021-01-30 18:43

I have a UIImageView whose image gets set via UIImagePicker

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPi         


        
8条回答
  •  臣服心动
    2021-01-30 19:17

    You can convert a UIImage to NSData like this:

    If PNG image

    UIImage *image = [UIImage imageNamed:@"imageName.png"];
    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
    

    If JPG image

    UIImage *image = [UIImage imageNamed:@"imageName.jpg"];
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    

    You can store it in CoreData like so (this is one possible useful solution):

    [newManagedObject setValue:imageData forKey:@"image"];
    

    You can load the data from CoreData like this:

    NSManagedObject *selectedObject = [[self yourFetchCOntroller] objectAtIndexPath:indexPath];
    UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"image"]];
    
    // Set the image to your image view  
    yourimageView.image = image;
    

提交回复
热议问题