下面的函数接受UIImage
并从 中返回 a CVPixelBuffer
,UIImage
但它删除了 alpha 通道。
class func pixelBufferFromImage(image: UIImage, pixelBufferPool: CVPixelBufferPool, size: CGSize) -> CVPixelBuffer {
var pixelBufferOut: CVPixelBuffer?
let status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pixelBufferPool, &pixelBufferOut)
if status != kCVReturnSuccess {
fatalError("CVPixelBufferPoolCreatePixelBuffer() failed")
}
let pixelBuffer = pixelBufferOut!
CVPixelBufferLockBaseAddress(pixelBuffer, [])
let data = CVPixelBufferGetBaseAddress(pixelBuffer)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: data, width: Int(size.width), height: Int(size.height),
bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
context!.clear(CGRect(x: 0, y: 0, width: size.width, height: size.height))
let horizontalRatio = size.width / image.size.width
let verticalRatio = size.height / image.size.height
//aspectRatio = max(horizontalRatio, verticalRatio) // ScaleAspectFill
let aspectRatio = min(horizontalRatio, verticalRatio) // ScaleAspectFit
let newSize = CGSize(width: image.size.width * aspectRatio, height: image.size.height * aspectRatio)
let x = newSize.width < size.width ? (size.width - newSize.width) / 2 : 0
let y = newSize.height < size.height ? (size.height - newSize.height) / 2 : 0
context!.draw(image.cgImage!, in: CGRect(x: x, y: y, width: newSize.width, height: newSize.height))
CVPixelBufferUnlockBaseAddress(pixelBuffer, [])
return pixelBuffer
}
- 我知道初始图像有一些特定的像素,
alpha = 0
因为如果我这样做po image.pixelColor(atLocation: CGPoint(x: 0, y: 0))
,它会打印
可选 - 一些:UIExtendedSRGBColorSpace 0 0 0 0
但生成的图像具有黑色背景。
我也尝试过使用CGImageAlphaInfo.premultipliedLast.rawValue
,但这会导致图像变蓝,所以我认为RGBA
toARGB
正在被交换。但是,具有讽刺意味的是,这意味着 B inARGB
是 255,这表明RGBA
A 将是 255,它应该是 0。
使用时如何正确地将UIImage
alpha 转换为 alpha ?CVPixelBuffer
CGContext
编辑1:
这是我的pixelBufferPool
.
func createPixelBufferAdaptor() {
let pixelFormatRGBA = kCVPixelFormatType_32RGBA //Fails
let pixelFormatARGB = kCVPixelFormatType_32ARGB //Works
let sourcePixelBufferAttributesDictionary = [
kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: pixelFormatARGB),
kCVPixelBufferWidthKey as String: NSNumber(value: Float(renderSettings.width)),
kCVPixelBufferHeightKey as String: NSNumber(value: Float(renderSettings.height))
]
pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoWriterInput,
sourcePixelBufferAttributes: sourcePixelBufferAttributesDictionary)
}
它仅在我使用kCVPixelFormatType_32ARGB
. 我所说的工作是指当我尝试使用缓冲池时
let status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pixelBufferPool, &pixelBufferOut)
if status != kCVReturnSuccess {
fatalError("CVPixelBufferPoolCreatePixelBuffer() failed")
}
如果我使用该版本,这将失败,RGBA
但如果我使用该ARGB
版本,则可以。