title: Best way to optimize image before uploading to server
body: <p>What's the best practice to optimize the weight of an image before uploading it on the server in iOS?</p>
  
  <p>The image can from the images library of the user or directly for the UIPicker - camera mode.</p>
  
  <p>I do have some requirements : a minimum upload resolution and a wished maximum upload size.</p>
  
  <p>Let 's say kMaxUploadSize = 50 kB
  and kMinUploadResolution = 1136 * 640</p>
  
  <p>What I currently do is :</p>
  
  <pre><code>while (UIImageJPEGRepresentation(img,1.0).length &gt; MAX_UPLOAD_SIZE){
      img = [self scaleDown:img withFactor:0.1];
  }
  NSData *imageData = UIImageJPEGRepresentation(img,1.0);
  
  -(UIImage*)scaleDown:(UIImage*)img withFactor:(float)f{
  
  CGSize newSize = CGSizeMake(img.size.width*f, img.size.height*f);
  
  UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0);
  [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
  UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  return scaledImage;
  </code></pre>
  
  <p>}</p>
  
  <p>The time spend in each loop is awfully, several seconds, which leads to a very long delay before effectively sending the image to the server.</p>
  
  <p>Any approach / idea / strategy ?</p>
  
  <p>Thanks a lot !</p>