ios - 如何在 Swift 3 中将 captureStillImageAsynchronously(sampleBuffer) 转换为 base64 编码

标签 ios swift swift3

如何在 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/

相关文章:

ios - 如何在根 TableView Controller 中通过 swift 在两个 TableView 之间建立 Segue 连接?

swift - 在 Swift XCode 8.2.1 中使用 @try/@catch 安全取消订阅

ios - Xcode & Swift - 检测 UIScrollView 内部 UIView 的用户触摸

ios - Swift 2 didSelectRowAtIndexPath UIAlertController 将 segue 推送到带有 4 个字符串的 TVC

ios - 选择带有数字的特定 UIButton

ios - 依赖于另一个 ios 框架项目的 podspec

ios - 表达式类型 'DataRequest' 在没有更多上下文 Swift 的情况下是不明确的

ios - 多个 View 中的手势

ios - 从 UIActivityViewController 中选择时显示的 MessageComposer 的 NavigationBar 和 BarButtonItem 颜色更改

ios - 如果 tableView 数据为空,如何显示另一个 View Controller