-1

In my app, I have a user select/take photo, which then goes to this method (standard stuff):

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

Now, how can i reduce the image to a certain file size (I want it to be reduced to somewhere around 80-90 kb).

crazyshark
  • 133
  • 1
  • 11

1 Answers1

1

A bit crude:

UIImage *image = (UIImage *)info[UIImagePickerControllerEditedImage];
NSData *data;
for (CGFloat quality = 1.0; CGFloat >= 0; CGFloat -= 0.05)
{
    data = UIImageJPEGRepresentation(image,quality);
    if (data.length < 90000)
        break;
}

Probably quite CPU-intensive. There are probably better ways to find the ideal quality more quickly.

jcaron
  • 17,302
  • 6
  • 32
  • 46
  • I would go with a binary search, but you've got the general idea. – user3386109 Jun 28 '14 at 01:00
  • maybe you should explain scaling as-well. compressing a full camera size image to 90KB might result in very bad quality. – vikingosegundo Jun 28 '14 at 01:01
  • @vikingosegundo, indeed, but the trade-off between size and quality is a decision that is up to the implementer. – jcaron Jun 28 '14 at 01:04
  • the question itself demonstrate that OP hasn't given much thought about what an UIImage is and how file size (if that is what he is talking about) relates to image representation. So expecting a educated guess about the trade-offs might be a litte heavy. – vikingosegundo Jun 28 '14 at 01:07
  • @jcaron Thanks, I believe that is along the lines of what I was looking for. Is there any way I can compress an Image using the compressionQuality aspect of UIImageJPEGRepresentation method (when converting to NSData)? The file size doesn't have to be dead on 90kb, I just need a compressed photo to upload to my server. – crazyshark Jun 28 '14 at 01:42
  • That's what the code above does. If you don't care about the specific size and have chosen a specific quality, just use `data = UIImageJPEGRepresentation(image,quality)`. As pointed out by @vikingosegundo, you may want to resize the image first to achieve the size you want, but that really depends on what you want to do with the image... – jcaron Jun 28 '14 at 01:45
  • @jcaron oh ok, i'll reduce the image proportions and then will reduce the file size. If I use the UIImageJPEGRepresentation method, is there anyway I can know what file size output I will get depending on the proportions of the image I send in and quality I set? – crazyshark Jun 28 '14 at 01:52
  • 1
    @crazyshark, it varies a lot depending on the contents of the image. A picture with large surfaces of a single colour or a slight gradient will compress a lot better than a picture with tons of very fine details. – jcaron Jun 28 '14 at 01:57