Article

Creating a Core Graphics Image Format

Provide descriptions of Core Graphics image formats for conversions to and from vImage.

Overview

Conversions between Core Graphics-backed images and vImage buffers require that you define the Core Graphics image format. The format describes the number of color channels and how they're ordered; the size, in bits, of the color channels; and whether the image data is premultiplied by an alpha value.

You can initialize a Core Graphics image format in either of two ways: by hard-coding values or by deriving the format properties from a CGImage instance.

Initialize a Core Graphics Image Format from Hard-Coded Values

The following example shows how you create a Core Graphics image format that describes an image containing four 8-bit channels in the following order: alpha (transparency), red, green, and blue. This combination of properties is referred to as ARGB8888.

The vImage_CGImageFormat structure created by this code is reusable. You declare it as a variable because it's passed to subsequent vImage functions as an in-out parameter.

var format = vImage_CGImageFormat(
    bitsPerComponent: 8,
    bitsPerPixel: 32,
    colorSpace: nil,
    bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.first.rawValue),
    version: 0,
    decode: nil,
    renderingIntent: .defaultIntent)

Passing nil to the colorSpace parameter creates an sRGB color space—the default in iOS. The colorSpace parameter requires an unmanaged CGColorSpace instance. If you want to pass an explicit color space, use the passRetained(_:) function; for example:

[...]
    colorSpace: Unmanaged.passRetained(CGColorSpaceCreateDeviceRGB()),
[...]

Initialize a Core Graphics Image Format from an Image

You can derive the properties of a Core Graphics image format from the CGImage instance itself. The following example shows how to create a format description based on the properties of a UIImage instance named sourceImage:

guard
    let cgImage = sourceImage.cgImage,
    let sourceColorSpace = cgImage.colorSpace else {
        print("Unable to initialize cgImage or colorSpace.")
        return nil
}
 
var sourceImageFormat = vImage_CGImageFormat(
    bitsPerComponent: UInt32(cgImage.bitsPerComponent),
    bitsPerPixel: UInt32(cgImage.bitsPerPixel),
    colorSpace: Unmanaged.passRetained(sourceColorSpace),
    bitmapInfo: cgImage.bitmapInfo,
    version: 0,
    decode: nil,
    renderingIntent: cgImage.renderingIntent)

See Also

First Steps

Creating and Populating Buffers from Core Graphics Images

Initialize vImage buffers from Core Graphics images.

Creating a Core Graphics Image from a vImage Buffer

Create displayable representations of vImage buffers.