用RealityKit拍照, 并存到相册

禁止转载

AR应用, 用RealityKit呈现, 要实现拍照与录像的功能, github上搜到有个库, 但是只支持ARSCNView, 而且感觉这个功能算是比较正常的功能吧, 竟然没搜到其他实现的, 踩了不少的坑只实现了拍照, 不过效果还算不错.

此方法只适用于iOS15及之后.


示例.png

开始的思路是获取到ARFrame的一帧, 然后给存到相册. 正好ARSessionDelegate的session(_ session: ARSession, didUpdate frame: ARFrame)方法会返回ARFrame, ARFrame包含capturedImage. 结果这个capturedImage是只有相机的内容, 看网上有人说他是拿到相机内容后再用metal把虚拟内容渲上去, 感觉直接用metal渲的可能还是少数吧.

然后我想到用ReplayKit去录屏, 但是用这种方法每次录屏都会弹出一个系统提示, 就也放弃这个方法了.

一筹莫展之际, 我想起了苹果官方postProcess的代码, 后期处理的话应该是相机与虚拟内容都渲好的图像. 试了一下果然是ok的. 流程大概是arView有renderCallbacks, 其中prepareWithDevice的回调获取ciContext, 然后postProcess的回调获取到CIImage, 再转成UIImage保存到相册.

在此之前, 先检查适合当前设备的输出材质的像素格式

@available(iOS 15.0, *)
extension RealityKit.ARView.PostProcessContext {
    // Returns the output texture, ensuring that the pixel format is
    // appropriate for the current device's GPU.
    var compatibleTargetTexture: MTLTexture! {
        if self.device.supportsFamily(.apple2) {
            return targetColorTexture
        } else {
            return targetColorTexture.makeTextureView(pixelFormat: .bgra8Unorm)!
        }
    }
}

注册prepareWithDevice的回调, 并保存CIContext

arView.renderCallbacks.prepareWithDevice = setupCoreImage
func setupCoreImage(device: MTLDevice) {
    // Create a CIContext and store it in a property.
    self.ciContext = CIContext(mtlDevice: device)

    // Do other expensive tasks, like loading images, here.
}

注册postProcess的回调, 获取需要的UIImage, 并渲染. 这里是与官方后期处理的代码不同的地方, 毕竟我只是想要一帧而不是想要后期处理. 所以如果对比的话会发现我删除了滤镜的部分.

arView.renderCallbacks.postProcess = postProcessWithCoreImage
func postProcessWithCoreImage(context: ARView.PostProcessContext) {

    // Convert the frame buffer from a Metal texture to a CIImage, and 
    // set the CIImage as the filter's input image.
    guard let input = CIImage(mtlTexture: context.sourceColorTexture) else {
        fatalError("Unable to create a CIImage from sourceColorTexture.")
    }

    // 确保只拿一帧
    if cameraState == .needCapture {
        cameraState = .captured
            
        DispatchQueue.main.async { [weak self] in
            // 因为渲染时的坐标系(左下0,0)与UIKit的坐标系(左上0,0)不同, 所以这里需要纵向镜像一下
            let upsideDown = input.oriented(.downMirrored)
            let image = UIImage(ciImage: upsideDown)
            // 获取到我们需要的UIImage
            self?.tempImage = image
        }
    }
    // 下面这部分代码的作用是把内容渲染到arView上
    // Create a render destination and render the filter to the context's command buffer.
    let destination = CIRenderDestination(mtlTexture: context.compatibleTargetTexture,
                                          commandBuffer: context.commandBuffer)
    destination.isFlipped = false
    _ = try? self.ciContext.startTask(toRender: input, to: destination)
}

最后是保存到相册

    func saveImage() {
        DispatchQueue.main.async { [weak self] in
            self?.saveJpg((self?.tempImage)!)
            let path = self?.documentDirectoryPath()?.appendingPathComponent("temp.jpg")
            let image = UIImage.init(contentsOfFile: path!.path)!
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(self?.saveImageComplete), nil)
        }
    }

    func saveJpg(_ image: UIImage) {
        if let jpgData = image.jpegData(compressionQuality: 0.5),
            let path = documentDirectoryPath()?.appendingPathComponent("temp.jpg") {
            try? jpgData.write(to: path)
        }
    }
    
    func documentDirectoryPath() -> URL? {
        let path = FileManager.default.urls(for: .documentDirectory,
                                            in: .userDomainMask)
        return path.first
    }

    @objc func saveImageComplete(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject) {
        if error == nil {
            showAlert(title: "图片已存至相册")
        } else {
            showAlert(title: "保存到相册失败")
        }
    }

保存相册这步看网上都是只有UIImageWriteToSavedPhotosAlbum这一步, 看方法描述的话确实感觉这个方法传一个UIImage就ok了, 结果是如果不把UIImage先给存下来的话, 会遇到下面未知错误, 贼坑

Error Domain=ALAssetsLibraryErrorDomain Code=-1 "未知错误" UserInfo={NSLocalizedDescription=未知错误, NSUnderlyingError=0x2832cefd0 {Error Domain=PHPhotosErrorDomain Code=3303 "(null)"}}

理论上postProcess那里可以拿到每秒60帧所以实现录像的话应该也可以, 但是我还没研究出来具体怎么实现所以有大佬的话可以指点一下.

我现在是全职做iOS AR开发, 感觉坑是真的多, 而且网上能搜到的内容比较少, 如果有跟我一样感受的不妨加个好友我们可以互相避坑.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

相关阅读更多精彩内容

友情链接更多精彩内容