Chameleon
Chameleon

Reputation: 1608

UIImage CompressionQuality not Linear

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"

Upvotes: 1

Views: 277

Answers (1)

Rog
Rog

Reputation: 18670

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;
}

Upvotes: 0

Related Questions