将UIImage转换为NSData并使用核心数据保存 [英] Convert UIImage to NSData and save with core data

查看:169
本文介绍了将UIImage转换为NSData并使用核心数据保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIImageView ,其图像通过 UIImagePicker设置

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

我尝试将此图像转换为 NSData 并使用核心数据保存:

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!

推荐答案

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

You can convert a UIImage to NSData like this:

如果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中(这是一个可能有用的解决方案):

You can store it in CoreData like so (this is one possible useful solution):

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

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

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;

这篇关于将UIImage转换为NSData并使用核心数据保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆