如何在 Swift 3 中将 captureStillImageAsynchronously(sampleBuffer) 转换为 base64 编码
我正在尝试将图像数据连续馈送到 HTML Web View ,发现没有 Cordova 插件可以满足此目标,因为我需要图像/视频数据在 Canvas 上绘制,以便我可以使用 js 库对其进行处理。
最初我想使用 WEBRTC,但它仅适用于 Android。我正在 iOS 9+ 上进行开发。
因此,我尝试创建一个非常简单的插件,实时显示预览并每 0.3 秒提供图像数据(使用 javascript Cordova 插入命令调用),以便处理图像。
获取sampleBuffer的快速教程: http://drivecurrent.com/using-swift-and-avfoundation-to-create-a-custom-camera-view-for-an-ios-app/
我需要的是将 captureStillImageAsynchronously sampleBuffer 转换为 base64 编码,或者是否有其他方法来获取可以由 javascript 处理的图像数据?
if let videoConnection = stillImageOutput!.connection(withMediaType: AVMediaTypeVideo) {
videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in
if (sampleBuffer != nil) {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let dataProvider = CGDataProvider(data: imageData as! CFData)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)
self.capturedImage.image = image
print(sampleBuffer) // how to convert this to 64encode ? without saving to camera roll
}
})
}
最佳答案
函数captureStillImageAsynchronously(from:completionHandler:)
已弃用,如我的评论中所述。您应该更新代码以使用新的 AVCapturePhotoOutput 类。
作为一般答案,您可以使用方法 base64EncodedData
将 NSData(Data,在 Swift 3 中)转换为 base64 编码数据:
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let base64Data = imageData.base64EncodedData([])
关于ios - 如何在 Swift 3 中将 captureStillImageAsynchronously(sampleBuffer) 转换为 base64 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42069545/