首页 > 解决方案 > CVPixelBuffer 到 CGImage 并按比例缩小

问题描述

我有以下代码要转换CVPixelBufferCGImage它工作正常:

let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))

// Get the number of bytes per row for the pixel buffer
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer!)

// Get the number of bytes per row for the pixel buffer
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!)
// Get the pixel buffer width and height
let width = CVPixelBufferGetWidth(imageBuffer!)
let height = CVPixelBufferGetHeight(imageBuffer!)

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

// Create a bitmap graphics context with the sample buffer data
let bitmap = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue|CGImageAlphaInfo.premultipliedFirst.rawValue)
let contextBM = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,
                                  bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmap.rawValue)
// Create a Quartz image from the pixel data in the bitmap graphics context
let quartzImage = contextBM!.makeImage()

//Unlock the pixel buffer
CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))

self.myCGImage = quartzImage

现在,我希望CGImage创建的尺寸更小。也许一半大小?是否可以在不运行任何额外内容的情况下修改上述代码?

标签: iosswiftcgimageciimage

解决方案


推荐阅读