将UIImage转换为NSData并使用核心数据保存

时间:2013-01-03 05:08:39

标签: ios objective-c core-data nsdata

我有一个UIImageView,其图片是通过UIImagePicker

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

我“尝试”将此图片转换为NSData并将其与核心数据一起保存:

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

然后我尝试将图像加载到单独的文件中:

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

我不明白为什么这不起作用。非常感谢任何帮助!

8 个答案:

答案 0 :(得分:58)

您可以将UIImage转换为NSData,如下所示:

如果是PNG图片

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

如果是JPG图片

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

你可以将它存储在CoreData中(这是一个可能有用的解决方案):

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

您可以像这样从CoreData加载数据:

NSManagedObject *selectedObject = [[self yourFetchCOntroller] objectAtIndexPath:indexPath];
UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"image"]];

// Set the image to your image view  
yourimageView.image = image;

答案 1 :(得分:10)

对于swift,它只是:

UIImageNSData

imageData = UIImagePNGRepresentation(image)

答案 2 :(得分:3)

用于存储在数据库:::

        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;

当您从数据库中获取该图像时,您可以编写以下代码...

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

我认为这对你很有帮助。

答案 3 :(得分:2)

在Mac OS上,您可以通过勾选模型中属性的可转换框,而不是选择特定的变换器,并将UIImage直接分配给属性,让Core Data为您处理。 / p>

我不确定它是否适用于iOS,但可能值得一试。

答案 4 :(得分:1)

要将图像转换为NSData,请尝试以下代码...

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

让我知道它的工作与否...... !!!

快乐编码!!!!

答案 5 :(得分:1)

尝试使用此代码保存图像数据

保存:

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试试这个:

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");
}

答案 6 :(得分:0)

此代码将您的图像数据保存到filedata中,您可以在任何地方使用

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

答案 7 :(得分:0)

这是我所做的以及它存储到nsdata的工作。

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

并使用此代码加载到图像

ImgProductType.image= [[UIImage alloc] initWithData:productTypeSub.imgSmall];