title: How to compress images in iOS?
body: <p>I have been looking through every stack overflow post and video online and I can't find a solution that works correctly. Right now the user selects a photo that I want to compress before uploading to an AWS S3 bucket. The upload works perfectly but for some reason, the compressed image is larger than the original image! For example, if the user selects a 9KB photo, when I upload to S3 the photo is 28.5KB. I tried a different photo and it's 48KB and after "compression" on S3 its 378.9KB! (I am using the latest software version of everything and compiling with the simulator)</p>
  
  <p>I want to compress the original image as much as I can before uploading.</p>
  
  <p>This is what I have so far:</p>
  
  <p><em>How I "compress" the image:</em></p>
  
  <pre><code>UIImage *compressedProductImage;
  NSData *NSproductImage;
  NSUInteger productImageSize;
  
  - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary&lt;NSString *,id&gt; *)info{
      self.productImage = info[UIImagePickerControllerOriginalImage];
      [self.productImageImageView setImage:self.productImage];
      [self dismissViewControllerAnimated:YES completion:nil];
  
      NSproductImage = UIImageJPEGRepresentation(self.productImage, 0.5f);
      productImageSize = [NSproductImage length];
  
      compressedProductImage = [UIImage imageWithData: NSproductImage];
  </code></pre>
  
  <p><em>How I upload the photo:</em></p>
  
  <pre><code>//Convert product UIImage
  NSArray *productImagePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *productImageFilePath = [[productImagePaths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@".png"]];
  [UIImagePNGRepresentation(compressedProductImage) writeToFile:productImageFilePath atomically:YES];
  NSURL *productImageFileUrl = [NSURL fileURLWithPath:productImageFilePath];
  
  uploadRequest.body = productImageFileUrl;//Needs to be a NSURL
  uploadRequest.bucket = AWS_BUCKET_NAME;
  uploadRequest.key = productImageKey;
  uploadRequest.contentType = @"image/png";
  uploadRequest.ACL = AWSS3BucketCannedACLPublicRead;
  
  [[transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) {
      if (task.error != nil) {
          NSLog(@"%s %@","Error uploading (product image):", uploadRequest.key);
      }else{
          NSLog(@"Product image upload completed");
      }
      return nil;
  }];
  </code></pre>