gpt4 book ai didi

ios - 将 UIImage 转换为 NSData 并与核心数据一起保存

转载 作者:IT王子 更新时间:2023-10-29 08:09:50 28 4
gpt4 key购买 nike

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

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

最佳答案

您可以像这样将 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;

关于ios - 将 UIImage 转换为 NSData 并与核心数据一起保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14133366/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com