0

Swift gives the error that a fileDataRepresentation cannot be created for AVCapturePhoto. Printing "photo", returns the photo's metadata. How can I convert the image to file bytes and eventually base64? I have tried many methods so far, but all rely on obtaining file bytes. Thanks for any responses in advance!

   @IBAction func takePhotoButtonPressed(_ sender: Any) {
          let settings = AVCapturePhotoSettings()
          let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first!
          let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType,
                               kCVPixelBufferWidthKey as String: 160,
                               kCVPixelBufferHeightKey as String: 160]
          settings.previewPhotoFormat = previewFormat
          settings.isHighResolutionPhotoEnabled = false
          sessionOutput.capturePhoto(with: settings, delegate: self)
        
    }

    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Swift.Error?) {
        let imageData = AVCapturePhoto.fileDataRepresentation()
Python 123
  • 59
  • 1
  • 13

1 Answers1

1

AVCapturePhoto.fileDataRepresentation is an instance method, NOT a class method.

You have to call it on an instance of AVCapturePhoto like this -

func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Swift.Error?) {
    let imageData = photo.fileDataRepresentation()
}
Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30
  • This method and converting it to a base64 image is creating a corrupt image. Is there any way to solve this? Code: let uiImage = UIImage(data: imageData!) let pngImage = uiImage?.pngData() let base64Data = pngImage!.base64EncodedString() – Python 123 Jun 17 '21 at 16:53
  • 1
    You should be able to convert this data into base64 string directly like `let base64String = photo.fileDataRepresentation()?.base64EncodedString()`. There's no need to go through this route `image > pngData > base64`. – Tarun Tyagi Jun 17 '21 at 20:07