2

我已将 UIImageview 转换为 NSData 并将其存储为二进制数据。但我不知道如何将二进制数据检索到 NSData 并将其转换为 UIImageview

我的代码在下面

图像保存为二进制数据----

-(void) save
{
    UIImage *img = [UIImage imageNamed:@"back2.png"];
    NSData *dataObj =UIImagePNGRepresentation(img);
    NotesDetails *notesDetails = (NotesDetails *) [NSEntityDescription insertNewObjectForEntityForName:@"NotesDetails" inManagedObjectContext:managedObjectContext];
 notesDetails.imageData=dataObj;
    NSLog(@"NotesDetails: %@",notesDetails);
    NSError *error;
    if (![managedObjectContext save:&error])
    {

    }
}

图像检索------

-(void)viewDidLoad
{
    NSFetchRequest *fectchreq = [[NSFetchRequest alloc] init];
    NSEntityDescription *entitydes = [NSEntityDescription entityForName:@"NotesDetails"
                                                 inManagedObjectContext:self.managedObjectContext];
    [fectchreq setEntity:entitydes];
    NSSortDescriptor *sortdes = [[NSSortDescriptor alloc] initWithKey:@"notesTime" ascending:YES];
    NSArray *sortdesarray = [[NSArray alloc] initWithObjects:sortdes, nil];
    [fectchreq setSortDescriptors:sortdesarray];
    NSError *error;
    NSMutableArray *storeddata = [[self.managedObjectContext executeFetchRequest:fectchreq error:&error] mutableCopy];

    if ([storeddata count] > 0)
    {
        for (NotesDetails *sc in storeddata)
        {
            imgFromDb=[NSData dataWithData:[@"%@",sc.imageData]];
        }
    }
    NSLog(@"Image : %@",imgFromDb);
    UIImageView *dbImage=[[UIImageView alloc]initWithFrame:CGRectMake(80,20,90,90)];
    dbImage.image=[UIImage imageWithData:imgFromDb];

    [NoteDetails addSubview:dbImage];
}
4

1 回答 1

3

您可以使用 NSKeyedUnarchiver:

imgFromDb= [NSKeyedUnarchiver unarchiveObjectWithData: sc.imageData];

如果你更喜欢它而不是 UIImagePNGRepresentation(),你可以用 NSKeyedArchiver 做相反的事情(对象到数据)。
还有其他方法可以做到这一点,例如:

imgFromDb= [UIImage imageWithData: sc.imageData];
于 2012-12-22T13:52:21.827 回答