swiftavcaptureoutput

Why are my AVCapturePhotoOutput file outputs so large?


I'm creating a camera app and everything is working well but the file-size of the photos that is being uploaded to Firebase are too big. They are in the 3MB category and I would like them to be in the ±600KB category.

I have set the AVCapturePhotoSettings.isHighResolutionPhotoEnabled to false but that does not appear to do anything and AVCapturePhotoOutput.quality.balanced only works for iOS13+ which is not going to work in my case.

Here is the delegate function that sends the image to my imageArray

extension NewPostFromPhoto: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    if let error = error {
        debugPrint (error)
    } else {

        photoData = photo.fileDataRepresentation()
        UIImageWriteToSavedPhotosAlbum(UIImage(data: photoData!)!, nil, nil, nil)
        self.imageArray.insert((UIImage(data: photoData!)?.fixOrientation())!, at:0)
        self.recentMediaCollection.reloadData()
    }
}

}

and here is my takePhoto() method:

func takeNewPhoto () {

    let settings = AVCapturePhotoSettings ()
    settings.isHighResolutionPhotoEnabled = false
    photoOutput?.capturePhoto(with: settings, delegate: self)
} 

Solution

  • Using your code I got pngData about 20 MB. But when we take jpegData(), we got about 2.2 MB.

    image.jpegData(compressionQuality: 0.8)
    

    Here full code from delegate

    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        guard let imageData = photo.cgImageRepresentation() else {
            self.captureFailed(error: error?.localizedDescription ?? "Can't take image from output")
            return
        }
        let cgimage = imageData.takeUnretainedValue()
        let orientation: UIImage.Orientation = captureDevice?.position == .front ? .leftMirrored : .right
        let image = UIImage(cgImage: cgimage, scale: 1, orientation: orientation)
        let data = image?.jpegData(compressionQuality: 0.8)
    }
    

    Hope its help