如何将AVCaptureStillImageOutput转换为UIImage并另存为NSData?

时间:2015-10-07 19:06:48

标签: ios uiimage swift2 nsdata avcapture

我正在尝试使用我正在处理的应用程序发送照片,我已经让应用程序拍摄照片,然后当您点按发送时它会发送您刚刚通过邮件发送的照片。

但我不知道如何将AVCaptureStillImageOutput类型的照片转换为UIImage并将其存储在NSData中,以便将其用作附件addAttachmentData

我试着这样做:

let data: NSData = UIImagePNGRepresentation(image: stillImageOutput)

我有这个功能

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

但它显示了一个错误,"使用未解析的标识符' imageAsUIIMage'

我想获取UIImage以通过电子邮件发送。

1 个答案:

答案 0 :(得分:1)

您可以捕获图像并将其保存到文件,并使用UIImage将其转换为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")
}