简体   繁体   中英

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.

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM