Handling HEIC/HEIF Images in Flutter

Madacode
1 min readFeb 21, 2023

--

We can’t run away from them.

When we develop for iOS, those devices do generate HEIC/HEIF images and previewing user-selected image in those format may be a hassle since Flutter didn’t provide first-party support for HEIC/HEIF images (source: https://github.com/flutter/flutter/issues/20522), leaving our custom image picker and asset preview implementation with blank spaces since we can’t preview HEIC/HEIF natively.

But don’t fret, we have another trick up our sleeve: converting them to supported format (JPG), in this short article, we will use a package named flutter_image_compress to get our job done.

Let’s add this line to your pubspec.yaml file:

dependencies:
flutter_image_compress: ^1.0.0-nullsafety

and run flutter pub get, then go to your custom image picker code and import:

import 'package:flutter_image_compress/flutter_image_compress.dart';

and now, go to your post-image picker result path processing code and do the following:

// assuming that the image path variable is named imagePath

final String imagePathLowerCase = imagePath.toLowerCase();

// you may also add another conditional to check, that is the platform iOS or macOS
if (imagePath.contains('heic') || imagePath.contains('heif)) {
final tmpDir = (await getTemporaryDirectory()).path;
final target = '$tmpDir/${DateTime.now().millisecondsSinceEpoch}.jpg';
final result = await FlutterImageCompress.compressAndGetFile(
imagePath,
target,
format: CompressFormat.jpg,
quality: 90,
);

if (result == null) {
// error handling here
}
}

this code snippet will happily convert your HEIC/HEIF selected image to JPG and now you can preview them in your Flutter app with no hassle.

That’s all for this article and see you in the next article.

--

--

Madacode

Senior Software Engineer @ Pinhome with 5+ years experience in various technologies including Go and Flutter. All posts are of my own opinion.