Saving images to Core Data?

Hello there,


basically I am trying to save images to Core data. I have set the data type to "Binary data", and also tried several methods of saving a selected image (both with User defaults) and with Core data. Could anyone please provide me with a proper working code for this? I know how to save other data like text and integers etc..


Thanks in advance.

Replies

Is this what you're looking for? :


yourEntityName.image = UIImagePNGRepresentation(theUIImage)

Hmm, I thought I had to convert my UIImage to a Data object before saving it? How is the process for displaying an image from Core data? uiimage.image = myEntity.image?

to create an image already stored in core data, you can use


+ (UIImage *)imageWithData:(NSData *)

data


You can use the function clane47 posted. That UIImagePNGRepresentation returns an NSData object. To if you have an existing UIImage, you can use the UIImagePNGRepresentation function, which returns the data, then assign it to the property.

Does this also work with the UIPickerView? Like, I select an image from my camera roll, then I convert it to NSData Object?


Btw, I am working in Swift 🙂

After you read in the managed object:


theImage = UIImage(data: yourEntityName.image!)

If you have an Entity in Core Data, and you want to give it an 'image' attribute to store images, like your original question asks...Core Data is capable of storing NSData. All you need to do, is get a data representation of a UIImage instance and assign it to the attribute (in ObjC or Swift if you make an NSManagedObject subclass for the entity...which you definitely should do, assign the data to the NSData property).


As mentioned already in this thread, to get a NSData representation of a UIImage you can use the UIImagePNGRepresentation function.


imageData = UIImagePNGRepresentation(existingUIImageObject);

myCoreDataEntity.imageData = imageData; //<--Image data is stored in the core data entity.



Now, when to reconstitute the image data back as a UIImage to show in your user interface, when you get the entity back out of Core Data you can use the class method I mentioned above in my previous post. If you are using Swift, just write it using the Swift syntax instead of ObjC. Claire47 has it posted.


Far as your question related to UIPickerView..I recall that a bug was introduced in iOS 7 that caused UIImageViews, when used inside a UIPickerView to not appear. I haven't tried to use UIPickerView with images in it in a long time, but it did break one of my apps years ago, and forced me to rewrite it using a UIPickerView clone. I have no idea if Apple has fixed that bug from iOS 7.

According to Apple it is possible when implemented properly: https://developer.apple.com/videos/play/wwdc2022/10119/