Search code examples
iosswiftcore-graphicsaccelerate-framework

Exporting 16 bit image with Swift in iOS


I would like to export a 16 bit image and I ahve the following code for it

let bv = malloc(width * height * 4)!
var db = vImage_Buffer(data: bv,
                               height: vImagePixelCount(height),
                               width: vImagePixelCount(width),
                               rowBytes: width*2)
//        vImageConvert_PlanarFtoPlanar8(&sourceBuffer, &destBuffer, 1.0, 0.0, vImage_Flags(kvImageNoFlags))
vImageConvert_PlanarFtoPlanar16F(&sourceBuffer, &db, vImage_Flags(kvImageNoFlags))
let bp = bv.assumingMemoryBound(to: UInt8.self)
let p = CGDataProvider(data: CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
                                                                bp,
                                                                width * height,
                                                                kCFAllocatorDefault))!

let cgImage = CGImage(width: width,
                      height: height,
                      bitsPerComponent: 5,
                      bitsPerPixel: 16,
                      bytesPerRow: width,
                      space: CGColorSpace(name: CGColorSpace.linearSRGB)!,
                      bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue),
                      provider: p,
                      decode: nil,
                      shouldInterpolate: false,
                      intent: .defaultIntent)!

let savePath = self.documentsPath.appendingPathComponent("camera")
let sURL = savePath.appendingPathComponent(String(format: "image.png")
if let imageDestination = CGImageDestinationCreateWithURL(smoothedSceneDepthURL as CFURL, kUTTypePNG, 1, nil) {
    CGImageDestinationAddImage(imageDestination, cgImage, nil)
    CGImageDestinationFinalize(imageDestination)
}

Apple documentation says those values for bitsPerComponent and bitsPerPixel are correct for iOS here

But I get the following error: [Unknown process name] CGImageCreate: invalid image bits/pixel or bytes/row.

I am able to export an 8 bit image in grayscale and can post the params if required btw


Solution

  • If there are 16 bits per pixel, then there will be 2*width bytes per row:

                      bytesPerRow: 2 * width,