iOS - Scale and crop CMSampleBufferRef/CVImageBufferRef

前端 未结 5 1511
广开言路
广开言路 2020-11-27 03:42

I am using AVFoundation and getting the sample buffer from AVCaptureVideoDataOutput, I can write it directly to videoWriter by using:

- (void)wr         


        
5条回答
  •  北海茫月
    2020-11-27 04:03

    Try this on Swift3

    func resize(_ destSize: CGSize)-> CVPixelBuffer? {
            guard let imageBuffer = CMSampleBufferGetImageBuffer(self) else { return nil }
            // Lock the image buffer
            CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
            // Get information about the image
            let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
            let bytesPerRow = CGFloat(CVPixelBufferGetBytesPerRow(imageBuffer))
            let height = CGFloat(CVPixelBufferGetHeight(imageBuffer))
            let width = CGFloat(CVPixelBufferGetWidth(imageBuffer))
            var pixelBuffer: CVPixelBuffer?
            let options = [kCVPixelBufferCGImageCompatibilityKey:true,
                           kCVPixelBufferCGBitmapContextCompatibilityKey:true]
            let topMargin = (height - destSize.height) / CGFloat(2)
            let leftMargin = (width - destSize.width) * CGFloat(2)
            let baseAddressStart = Int(bytesPerRow * topMargin + leftMargin)
            let addressPoint = baseAddress!.assumingMemoryBound(to: UInt8.self)
            let status = CVPixelBufferCreateWithBytes(kCFAllocatorDefault, Int(destSize.width), Int(destSize.height), kCVPixelFormatType_32BGRA, &addressPoint[baseAddressStart], Int(bytesPerRow), nil, nil, options as CFDictionary, &pixelBuffer)
            if (status != 0) {
                print(status)
                return nil;
            }
            CVPixelBufferUnlockBaseAddress(imageBuffer,CVPixelBufferLockFlags(rawValue: 0))
            return pixelBuffer;
        }
    

提交回复
热议问题