How to open a HEIF (.heic) image?

16.7k views Asked by At

For a c++ project, I need to open and show a HEIF (.heic) image. What I know (if I'm right) is that the HEIF images are based on the ffmpeg standard, and requires a H265 codec to be read.

I found several open-source H265 codecs:

I can open and show H265 encoded video files with each of them, but I'm unable to simply open, show or convert a .heic image. All of them return an error, or just do nothing.

To be honest I'm a little puzzled, because the HEIF standard seem to be a well kept secret. I'm unable to find a relevant info that could allow me to walk to a solution. Those I found are just tricks and workarounds, like e.g. forcing the device (I'm speaking here about the Apple iPhone using the new iOS11) to generate a jpg image instead of a heic, or using a third party application like dr.fone. Of course these solutions are irrelevant for me.

So, somebody can tell me which codec I should use with a .heif image, and how I can use it to open it? Or are there open source libraries or examples that allow to manipulate this type of image file? Somebody can point me to the good direction?

2

There are 2 answers

3
Ronald S. Bultje On

An example viewer specific for HEIF from Nokia is available here. I also tested directly with FFmpeg and it's able to open (play/decompress) the provided conformance files.

4
mwfearnley On

libheif seems to be a pretty active LGPL library for HEIF, with a C API. From the README:

The library has a C API for easy integration and wide language support. Note that the API is still work in progress and may still change.

The decoder automatically supports both HEIF and AVIF through the same API. No changes are required to existing code to support AVIF. The encoder can be switched between HEIF and AVIF simply by setting heif_compression_HEVC or heif_compression_AV1 to heif_context_get_encoder_for_format().

Loading the primary image in an HEIF file is as easy as this:

heif_context* ctx = heif_context_alloc();
heif_context_read_from_file(ctx, input_filename, nullptr);

// get a handle to the primary image
heif_image_handle* handle;
heif_context_get_primary_image_handle(ctx, &handle);

// decode the image and convert colorspace to RGB, saved as 24bit interleaved
heif_image* img;
heif_decode_image(handle, &img, heif_colorspace_RGB, heif_chroma_interleaved_RGB, nullptr);

int stride;
const uint8_t* data = heif_image_get_plane_readonly(img, heif_channel_interleaved, &stride);

A nice, Emscripten-powered demo is available which actually allows you to load and view HEIF files directly inside a browser.