Search code examples
swiftpngcore-image

How do I export a 16 bit PNG in macOS using the ciContext.writePNGRepresentation(of: , to:, format:,colorSpace:, options:) API?


Is it possible to export a 16bit image using this API ?

ciContext.writePNGRepresentation(of: , to:, format:,colorSpace:, options:)

I am able to export 10bit HEIF files using the HEIF10 API

ciContext.writeHEIF10Representation(of:, to:, colorSpace:, options:)

These are the parameters being used

 let options = [kCGImageDestinationLossyCompressionQuality as CIImageRepresentationOption: 1.0 as CGFloat]
 let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
 let imgFormat = CIFormat.RGBA8

I tried using CIFormat.RGBA16 but that seems to make no difference to the HEIF export which appears to always be 10bit - as expected.

EDIT: I tried some additional options that also appear to make no difference

let options = [kCGImageDestinationLossyCompressionQuality as CIImageRepresentationOption: 1.0 as CGFloat,
                       kCGImagePropertyDepth as CIImageRepresentationOption: 64,
                       kCGImagePropertyPixelFormat as CIImageRepresentationOption: 0x16]
        let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
        let imgFormat = CIFormat.RGBAh

Solution

  • You can export 16-bit PNG by passing the CIFormat.RGBA16 to writePNGRepresentation(...).

    HEIF doesn't support 16-bit exports, only 8-bit and 10-bit. For 8-bit, use the writeHEIFRepresentation(...) method and pass .RGBA8 or .BGRA8 as format. For 10-bit, use the specific writeHEIF10Representation(...) method.