title: How does snapchat resize images?
body: <p>How does SnapChat resize images into such small file sizes while still keeping decent quality? My images are saving at around 90KB for the back camera and 45kb for the front camera. I read online that sending a single snap is around 15kb. How can I optimize images better?</p>
  
  <p>Here is my code that takes a picture, resizes and optimizes it for posting:</p>
  
  <pre><code>// Takes a still image of a video, then resizes image while user is deciding whether to post or retake it
  @IBAction func takePictureButton(_ sender: Any) {
  
      if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo){
          videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait
          stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {
              (sampleBuffer, error) in
  
              if sampleBuffer != nil {
  
                  self.takePicture.isHidden = true
                  self.rotate.isHidden = true
                  self.back.isHidden = true
                  self.save.isHidden = false
                  self.retake.isHidden = false
  
                  let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                  let dataProvider = CGDataProvider(data: imageData as! CFData)
                  let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
  
                  // Handles scaling image while user decides whether or not to post or retake
                  // Scale this up for smaller images.. idk why
                  let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)
                  let size = image.size.applying(CGAffineTransform(scaleX: 0.4, y: 0.4))
  
                  UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
                  image.draw(in: CGRect(origin: .zero, size: size))
  
                  let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
                  UIGraphicsEndImageContext()
  
                  self.imageDataToSend = UIImageJPEGRepresentation(scaledImage!, 0.4)
                  self.imageToUpload = image
                  self.didTakePhoto = true
                  self.tempImageView.image = image
                  self.tempImageView.isHidden = false
                  self.captureSession?.stopRunning()
              }
          })
      }
  }
  </code></pre>