Convert UIImage to NSData and save with core data

2019-03-08 11:10发布

I have a UIImageView whose image gets set via UIImagePicker

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.gImage.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
}

I "attempt" to convert this image to NSData and save it with core data:

NSData *imageData = UIImagePNGRepresentation(self.gImage.image);
NSString *savedData = [[NSString alloc]initWithData:imageData encoding:NSUTF8StringEncoding];

//am is a pointer to my entities class. imageData is just a NSString attribute
am.imageData = savedData;

NSError *error;
if (![self.managedObjectContext save:&error]) {
    //Handle Error
} else {
    [self dismissViewControllerAnimated:YES completion:nil];
}

Then I try to load the image in a separate file:

self.cell.gImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.myEntity.imageData]]];

I cannot see why this is not working. Any help is greatly appreciated!

8条回答
beautiful°
2楼-- · 2019-03-08 12:07

Here is what I have done and its working for storing to nsdata.

[productTypeSub setValue:[[NSData alloc] initWithContentsOfURL:[NSURL  URLWithString:url]] forKey:@"imgSmall"];

and loading to image with this code

ImgProductType.image= [[UIImage alloc] initWithData:productTypeSub.imgSmall];
查看更多
萌系小妹纸
3楼-- · 2019-03-08 12:08

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;
查看更多
登录 后发表回答