Search code examples
iosuiimageswift2nsdataavcapture

How to convert AVCaptureStillImageOutput to UIImage and save as NSData?


I am trying to send a photo with the app I am working on, I have made the app to take a photo and then when you tap on send it would send the photo you just took to send it through mail.

But I don't know how to convert the photo that is of type AVCaptureStillImageOutput to UIImage and store it in a NSData in order to use it as an attachment in addAttachmentData.

I tried to do this:

let data: NSData = UIImagePNGRepresentation(image: stillImageOutput)

I have this function

func doSomethingWithImage(image: UIImage) {
        // do something here
        mc.addAttachmentData(UIImageJPEGRepresentation(UIImage(named: imageAsUIIMage)!, CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "backupOne.jpeg")
    }

But It shows me an error, "Use of unresolved identifier 'imageAsUIIMage'

I want to get the UIImage in order to send it through an e-mail.


Solution

  • You can get capture an image and save it to file and convert it to UIImage using stillImageOutput.captureStillImageAsynchronouslyFromConnection()

    // setup code
    stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
    
    captureSession.startRunning()
    
    let connection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
        stillImageOutput.captureStillImageAsynchronouslyFromConnection(connection) { (sampleBuffer, error) in
        // NSData of jpeg data. Save to file and add as email attachment.
        let jpegData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
    
        dispatch_async(dispatch_get_main_queue(), {
            self.doSomethingWithJPEGImageData(jpegData!)
        })
    }
    
    // later on
    func doSomethingWithJPEGImageData(jpegData: NSData) {
        mc.addAttachmentData(jpegData, mimeType: "image/jpeg", fileName: "backupOne.jpeg")
    }