قالب وردپرس درنا توس
Home / IOS Development / ios – UIImage obtain CVPixelBuffer removes Alpha

ios – UIImage obtain CVPixelBuffer removes Alpha



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

  class func pixelBufferFromImage (image: UIImage, pixelBufferPool: CVPixelBufferPool, size: CGSize) -> CVPixelBuffer {

was pixelBufferOut: CVPixelBuffer?

la status = CVPixelBufferPoolCreatePixelBuffer (kCFAllocatorDefault, pixelBufferPool, & pixelBufferOut)
if status! = kCVReturnSuccess {
fatalError ("CVPixelBufferPoolCreatePixelBuffer () failed")
}

la pixelBuffer = pixelBufferOut!

CVPixelBufferLockBaseAddress (pixelBuffer, [])

la data = CVPixelBufferGetBaseAddress (pixelBuffer)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB ()
let context = CGContext (data: data, width: Int (size. width), height: Int (size. height),
bitPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow (pixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)

context!. clear (CGRect (x: 0, y: 0, width: size. width, height: size. height))

la horizontalRatio = size.width / image.size.width
la verticalRatio = size.height / image.size.height
// aspectRatio = max (horizontalRatio, verticalRatio) // ScaleAspectFill
la aspectRatio = min (horizontalRatio, verticalRatio) // ScaleAspectFit

la newSize = CGSize (width: image.size.width * aspectRatio, height: image.size.height * aspectRatio)

la x = newSize.width <size.width? (size. width - newSize.width) / 2: 0
la y = newSize.height <size.height? (size.height - newSize.height) / 2: 0

context!


CVPixelBufferUnlockBaseAddress (pixelBuffer, [])

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

Optional
̵

1; some: UIExtendedSRGBColorSpace 0 0 0 0

but the resulting image has a black background.

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

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


Source link