CMSampleBuffer To UIImage

func sampleBufferToImage(_ sampleBuffer: CMSampleBuffer) -> UIImage? {


        guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }

        CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))

        letbaseAddress =CVPixelBufferGetBaseAddress(imageBuffer)

        letbytesPerRow =CVPixelBufferGetBytesPerRow(imageBuffer)

        letwidth =CVPixelBufferGetWidth(imageBuffer)

        letheight =CVPixelBufferGetHeight(imageBuffer)

        let colorSpace = CGColorSpaceCreateDeviceRGB()

        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)

        guardletcontext =CGContext(data: baseAddress,

                                      width: width,

                                      height: height,

                                      bitsPerComponent:8,

                                      bytesPerRow: bytesPerRow,

                                      space: colorSpace,

                                      bitmapInfo: bitmapInfo.rawValue)else{returnnil}

        guardletcgImage = context.makeImage()else{returnnil}

        CVPixelBufferUnlockBaseAddress(imageBuffer,CVPixelBufferLockFlags(rawValue: 0));

        returnUIImage(cgImage: cgImage)

    }

推荐阅读更多精彩内容