How can I create a CGImage from a HEIF-encoded image file in Objective-C, similar to how I load JPEG and PNG files?

I’m currently using Objective-C to load JPEG and PNG files into a CGImage, as shown in this code snippet:

imgDataProvider = CGDataProviderCreateWithFilename( [imgFilepath UTF8String] );

if( [[imgFilepath pathExtension] isEqualToString: @"png"] )
{
    image = CGImageCreateWithPNGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);
}
else if( [[imgFilepath pathExtension] isEqualToString: @"jpg"] || [[imgFilepath pathExtension] isEqualToString: @"jpeg"] )
{
    image = CGImageCreateWithJPEGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);
}

However, I’ve run into a problem with HEIF (High Efficiency Image File Format) images. There doesn’t seem to be a CGImageCreateWith… function variant for HEIF like there is for PNG and JPEG. I’m looking for a way to create a CGImage from a HEIF encoded image file. What approach or function can I use to load HEIF images similarly?

1 Like

To handle HEIF images and convert them into CGImage in Objective-C, you’ll need to use a slightly different approach since there’s no direct CGImageCreateWith… function for HEIF. You can utilize CIImage for this purpose, followed by a conversion to CGImage. Here’s an example of how to implement this:


NSURL *fileURL = [NSURL fileURLWithPath:imgFilepath];

CIImage *ciImage = [CIImage imageWithContentsOfURL:fileURL];

CIContext *context = [CIContext context];

CGImageRef cgImage = [context createCGImage:ciImage fromRect:[ciImage extent]];

In this code, you first create a CIImage from the HEIF file. Then, using CIContext, you convert the CIImage to a CGImage. This method is effective because CIImage supports HEIF, and you can leverage Core Image’s functionality for the conversion to CGImage.

Does this approach impact the image’s quality or the performance compared to the direct loading methods for JPEG and PNG?

Converting HEIF images to CGImage using CIImage and CIContext might be a bit slower than directly using CGImageCreateWithJPEGDataProvider or CGImageCreateWithPNGDataProvider, due to the extra conversion step. However, this performance difference is generally minor for most use cases.

Regarding image quality, this method should maintain the original quality of the HEIF image, as both CIImage and CGImage are well-equipped to handle high-resolution images without quality loss.