Convert UIImage to NSData and save with core data

2019-03-08 11:34发布

问题:

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!

回答1:

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;


回答2:

For swift its just:

UIImage to NSData

imageData = UIImagePNGRepresentation(image)


回答3:

For storing in database:::

        NSInteger RandomIndex = arc4random() % 1000; 
        NSString *randomImageName =[NSString stringWithFormat:@"Image%i.png",RandomIndex]; 
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:randomImageName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:savedImagePath error:nil];
            NSLog(@"file removed from path");
        }
        NSLog(@"Saved Image Path : %@",savedImagePath);
         NSData* imageData = UIImagePNGRepresentation (image1 ); 
        [imageData writeToFile:savedImagePath atomically:YES];

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

When you get that image from data base, you can write following code...

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:randomImageName];
NSData *myData = [NSData dataWithContentsOfFile:savedImagePath];
        UIImage *selectedImage = [UIImage imageWithData:myData];

I think it is helpful to you.



回答4:

On Mac OS you can let Core Data handle this for you by ticking the Transformable box on the attribute in the model, not selecting a specific transformer, and assigning the UIImage directly to the property.

I'm not sure if it works on iOS but it might be worth a try.



回答5:

To convert an image to NSData try below code...

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

let me know it is working or not..!!!

Happy Coding!!!!



回答6:

Try This Code to save image data

to save:

NSManagedObjectContext *context = [self managedObjectContext];

newsObj = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:context];

NSData *imageData = UIImagePNGRepresentation(self.gImage.image);

[newsObj setValue:imageData forKey:@"imgPng"];

NSError *error;

@try{

    if (managedObjectContext != nil) {

        if (![managedObjectContext save:&error]) {

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);


        } 
    }

}@catch (NSException *exception) {

    NSLog(@"inside exception");
}

To Retrive Try this:

NSManagedObjectContext *context = [self managedObjectContext];

    NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity1 = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];

    [fetchRequest setEntity:entity1];

    NSError *error;

    NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    if (array == nil) {

        NSLog(@"Testing: No results found");

    }else {

        NSLog(@"Testing: %d Results found.", [array count]);
    }

    NSData * dataBytes = [[array objectAtIndex:0] imgPng];;

    image = [UIImage imageWithData:dataBytes];

    [fetchRequest release]; 


}

@catch (NSException *exception) {

    NSLog(@"inside exception");
}


回答7:

This code save your image data into filedata and you can use it anywhere

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

    {

        CGSize destinationSize = CGSizeMake(170,170);

        UIGraphicsBeginImageContext(destinationSize);

       [image1 drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];

       UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

       UIGraphicsEndImageContext();

       NsData *filedata  = UIImagePNGRepresentation(newImage);

       [picker dismissModalViewControllerAnimated:YES];
   }
}


回答8:

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];