18

我有一个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]]];

我不明白为什么这不起作用。任何帮助是极大的赞赏!

4

8 回答 8

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;
于 2013-01-03T05:15:02.257 回答
10

为了迅速,它只是:

UIImageNSData

imageData = UIImagePNGRepresentation(image)
于 2015-05-16T01:01:58.813 回答
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];

我觉得对你有帮助。

于 2013-01-03T05:25:25.497 回答
2

在 Mac OS 上,您可以让 Core Data 为您处理这个问题,方法是在模型中的属性上勾选Transformable框,不选择特定的转换器,并将 UIImage 直接分配给属性。

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

于 2013-01-03T05:39:27.570 回答
1

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

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

让我知道它是否工作..!!!

快乐编码!!!!

于 2013-01-03T05:10:21.140 回答
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");
}

要检索试试这个:

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");
}
于 2013-01-03T05:29:39.700 回答
0

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

-(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];
   }
}
于 2013-01-03T05:33:38.243 回答
0

这是我所做的及其用于存储到 nsdata 的工作。

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

并使用此代码加载到图像

ImgProductType.image= [[UIImage alloc] initWithData:productTypeSub.imgSmall];
于 2013-10-21T21:17:14.480 回答