Creating and Populating Buffers from Core Graphics Images

Initialize vImage buffers from Core Graphics images.


vImage_Buffer structures are the basic data structures that vImage uses for working with images. They describe an image's dimensions and contain the pixel data that vImage routines operate on.

Typically, you'll initialize a source buffer from an image and initialize and allocate a destination buffer to receive the result of a vImage operation.

Initialize a Source Buffer from a Core Graphics Image

The vImage functions that initialize a buffer's size and data require an instantiated vImage_Buffer structure. Typically, you declare a buffer as a variable because these functions mutate the buffer:

var sourceBuffer = vImage_Buffer()

You can initialize a vImage buffer from a CGImage instance that's acquired from the cgImage property of an image. In the following example, the image is named Flowers_2.jpg. The vImageBuffer_InitWithCGImage(_:_:_:_:_:) function initializes a vImage_Buffer structure with the image data using the format discussed in Creating a Core Graphics Image Format.

    let sourceImage = UIImage(named: "Flowers_2.jpg"),
    let image = sourceImage.cgImage else {
        print("unable to create CGImage")

var error = kvImageNoError
error = vImageBuffer_InitWithCGImage(&sourceBuffer,

guard error == kvImageNoError else {
    fatalError("Error in vImageBuffer_InitWithCGImage: \(error)")

Many vImage functions return an error value. For example, if you pass an image that doesn't contain four 8-bit channels, vImageBuffer_InitWithCGImage(_:_:_:_:_:) returns kvImageInvalidImageFormat. To verify that the operation completed correctly, check the error value that the function returns.

Initialize and Allocate a Destination Buffer

Typically, in addition to creating a buffer to represent your source image, you create a destination buffer to receive the result of the vImage operation. In this case, you use the vImageBuffer_Init(_:_:_:_:_:) function to initialize a buffer of a specified size and the correct memory allocation for the bit-depth of the image:

var destinationBuffer = vImage_Buffer()
error = vImageBuffer_Init(&destinationBuffer,
guard error == kvImageNoError else {
    fatalError("Error in vImageBuffer_Init: \(error)")

Free the Buffer Memory

After you're finished with buffers that have have their own memory allocation, it's important that you free the memory allocated to them:


See Also

First Steps

Creating a Core Graphics Image Format

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

Creating a Core Graphics Image from a vImage Buffer

Create displayable representations of vImage buffers.