如何将BGRA帧的缓冲区转换为UIImage

时间:2019-03-07 22:14:10

标签: ios uiimage buffer cgcontext quartz

我目前正在尝试对iOS应用进行编程,以查看在Mac上使用usbmuxd通过Java程序通过TCP套接字发送的帧时出现此错误。

2019-03-07 14:03:59.539127-0800 Dashboard[26848:9393967] [Unknown process name] copy_read_only: vm_copy failed: status 1.

目前我不知道为什么它失败了,但是失败的那一行是底部的UIImage.init调用。

任何帮助将不胜感激。

代码:

class ViewController: UIViewController {

    @IBOutlet weak var cameraView: UIImageView!

    func echoService(client: TCPClient) {
        print("New client from:\(client.address)[\(client.port)]")
        var d = client.read(1280 * 720 * 4)
        var image = self.imageFromSampleBuffer(sampleBuffer: d!)
        cameraView.image = image
        client.close()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let server = TCPServer(address: "127.0.0.1", port: 5000)
        switch server.listen() {
        case .success:
            while true {
                if var client = server.accept() {
                    echoService(client: client)
                } else {
                    print("accept error")
                }
            }
        case .failure(let error):
            print(error)
        }
    }

    func imageFromSampleBuffer(sampleBuffer : Any) -> UIImage
    {

        var inputBuffer = sampleBuffer

        // Create a device-dependent RGB color space
        let colorSpace = CGColorSpaceCreateDeviceRGB();

        // Create a bitmap graphics context with the sample buffer data
        var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
        bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
        let context = CGContext(data: &inputBuffer, width: 1280, height: 720, bitsPerComponent: 8,
                                bytesPerRow: 1280 * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue);
        // Create a Quartz image from the pixel data in the bitmap graphics context
        let quartzImage = context!.makeImage();

        // Create an image object from the Quartz image
        let image = UIImage.init(cgImage: quartzImage!);

        return (image);
    }
}

0 个答案:

没有答案