Roi Mulia
Roi Mulia

Reputation: 5896

getting uncompressed CIImage data

I'm trying to get CIImage uncompress data. For now the only way I found to get compressed data is using CIContext as follow:

let ciContext = CIContext()

let ciImage = CIImage(color: .red).cropped(to: .init(x: 0, y: 0, width: 192, height: 192))

guard let ciImageData = ciContext.jpegRepresentation(of: ciImage, colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, options: [:]) else {
    fatalError()
}

print(ciImageData.count) // Prints 1331

Is it possible to get (as efficiently as possible) the uncompressed CIImage data?

Upvotes: 0

Views: 1230

Answers (1)

Frank Rupprecht
Frank Rupprecht

Reputation: 10398

As you can see, ciContext.jpegRepresentation is compressing the image data as JPEG and gives you a Data object that can be written as-is as a JPEG file to disk (including image metadata).

You need to use a different CIContext API for rendering directly into (uncompressed) bitmap data:

let rowBytes = 4 * Int(ciImage.extent.width) // 4 channels (RGBA) of 8-bit data
let dataSize = rowBytes * Int(ciImage.extent.height)
var data = Data(count: dataSize)
data.withUnsafeMutableBytes { data in
    ciContext.render(ciImage, toBitmap: data, rowBytes: rowBytes, bounds: ciImage.extent, format: .RGBA8, colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!)
}

Alternatively, you can create a CVPixelBuffer with the correct size and format and render into that with CIContext.render(_ image: CIImage, to buffer: CVPixelBuffer). I think Core ML has direct support for CVPixelBuffer inputs, so this might be the better option.

Upvotes: 5

Related Questions