Tuesday, 6 August 2019

UIImage obtaining CVPixelBuffer Removes Alpha

The function below takes in an UIImage and returns a CVPixelBuffer from the UIImage but it removes the alpha channel.

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
    }

  1. I know the initial image has some pixels with a specific alpha = 0 because if I do po image.pixelColor(atLocation: CGPoint(x: 0, y: 0)) it prints

Optional - some : UIExtendedSRGBColorSpace 0 0 0 0

but the resulting image has a black background.

I also tried using CGImageAlphaInfo.premultipliedLast.rawValue but that results in the image being blue, so I assume the RGBA to ARGB are getting swapped. But, ironically, that would mean that B in ARGB is 255 which would indicate that in RGBA that A would be 255, which it should be 0.

How can I correctly get the UIImage alpha to translate into the CVPixelBuffer when using CGContext?



from UIImage obtaining CVPixelBuffer Removes Alpha

No comments:

Post a Comment