ios 将 UIImage 转换为 NSData 并与核心数据一起保存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14133366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert UIImage to NSData and save with core data
提问by Bad_APPZ
I have a UIImageView
whose image gets set via UIImagePicker
我有一个UIImageView
其图像通过设置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
并将其与核心数据一起保存:
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!
我不明白为什么这不起作用。任何帮助是极大的赞赏!
回答by Nitin Gohel
You can convert a UIImage to NSData like this:
您可以像这样将 UIImage 转换为 NSData:
If PNG image
如果 PNG 图片
UIImage *image = [UIImage imageNamed:@"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
If JPG image
如果 JPG 图片
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):
您可以像这样将其存储在 CoreData 中(这是一种可能有用的解决方案):
[newManagedObject setValue:imageData forKey:@"image"];
You can load the data from CoreData like this:
您可以像这样从 CoreData 加载数据:
NSManagedObject *selectedObject = [[self yourFetchCOntroller] objectAtIndexPath:indexPath];
UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"image"]];
// Set the image to your image view
yourimageView.image = image;
回答by RiceAndBytes
For swift its just:
对于 swift 来说,它只是:
UIImage
to NSData
UIImage
到 NSData
imageData = UIImagePNGRepresentation(image)
回答by Prasad G
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.
我认为这对你有帮助。
回答by paulmelnikow
On Mac OS you can let Core Data handle this for you by ticking the Transformablebox on the attribute in the model, not selecting a specific transformer, and assigning the UIImage directly to the property.
在 Mac OS 上,您可以让 Core Data 为您处理这个问题,方法是在模型中的属性上勾选可转换框,而不是选择特定的转换器,并将 UIImage 直接分配给属性。
I'm not sure if it works on iOS but it might be worth a try.
我不确定它是否适用于 iOS,但可能值得一试。
回答by NiravPatel
To convert an image to NSData try below code...
要将图像转换为 NSData,请尝试以下代码...
UIImage *image = [UIImage imageNamed:@"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
let me know it is working or not..!!!
让我知道它是否有效..!!!
Happy Coding!!!!
编码快乐!!!
回答by Siba Prasad Hota
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");
}
回答by Abhishek
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];
}
}
回答by kemalony
Here is what I have done and its working for storing to nsdata.
这是我所做的及其用于存储到 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];