I have a CoreData Entity “GameSession” with an attribute “photo” which is of type “Binary Data” (and I clicked on “Allows External Storage”).
In a view, I save a photo in that attribute, like that:
PhotosPicker(selection: $selectedItem ,matching: .images) {
Label("Select a photo", systemImage: "photo")
}
.onChange(of: selectedItem) { newItem in
Task {
if let data = try? await newItem?.loadTransferable(type: Data.self) {
selectedPhotoData = data
}
}
}
Then I save it in my CoreData Entity “GameSession” in the attribute “photo” which is of type “Binary Data”, like that
let newSession = GameSession(context: self.moc)
newSession.date = self.date
newSession.setValue(self.selectedPhotoData, forKeyPath: "photo")
self.moc.save()
Everything works fine but I am wondering if I am not going to hit a memory issue when I will have a high number of “session” (and so a high number of photo).
Moreover, In my application, I only display the photo in a small square of 300 pixel by 300 pixels. So I don’t really need to store it in my coredata entity in high resolution.
How could I reduce the size of the photo BEFORE saving it? I guess I have to apply a “reduce_size” function to “selectedItem” or “newItem” in my PhotosPicker, but I don’t know how.
I know there is UIImageJPEGRepresentation that I could use and apply a compression ratio, But how to use that method on $selectedItem ?
Thanks and regards