1

I would like to save a UIImage to a CoreData Entity.

Per accepted answer here, in order to save this UIImage to the same Entity Table, suggested size of UIImage should be < 100kb

Thus when user takes a UIImage from a UIImagePickerController (either library or camera), I would like to do a UIImageJPEGRepresentation @ CompressionQuality rate that would render this UIImage data < 100kb

Playing around with

let imgData: NSData = UIImageJPEGRepresentation(CameraImage, <#compressionQuality: CGFloat#>)
let size = imgData.length

I've realized that 0.8 is not equivalent to 80% Data size of 1.0 compression.


How could I take any UIImage of any size and compress it down to data: with a size of 100kb maximum, so that as much integrity is held while allowing the size to be small enough to store in CoreData Entity?

NOTE: my original idea was to test size of UIImage then compress it @ "rate X = 100,000/size"

Community
  • 1
  • 1
Chameleon
  • 1,608
  • 3
  • 21
  • 39

1 Answers1

0

You do not need to downsize your image to be under 100kb, all you have to do is create a Coredata attribute of type binary and tick the "Allows External Storage" box. Coredata will take care of the rest for you:

  1. Create an attribute named imageData of type binary and allowing for external storage
  2. Create a transient attribute named 'image' and implement custom getters and setters as per below:

Files larger than 1MB will be stored on a separate folder relative to your database folder whereas smaller files are saved directly to the sqlite file.

- (void)setImage:(UIImage*)image
{
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    if (data) {
        [self setImageData:data];
    }
}

- (UIImage*)image
{
    UIImage *image = [UIImage imageWithData:self.imageData];
    return image;
}
Rog
  • 18,602
  • 6
  • 76
  • 97
  • Ok but I have a TableView which shows all CoreData entities `Person` and displays each entry's image(possibly 200+ images)...which unless these images are compressed could crash the App, No? – Chameleon Apr 28 '15 at 22:14
  • In that case you should also create a thumbnail size version of your image to display in the tableview. This is not strictly necessary as if you do things correctly only the cells being displayed will have the images loaded (i.e. you may have 5-10 images shown on screen at any given time and when the user scrolls an image is unloaded while a new one is loaded). – Rog Apr 29 '15 at 02:42