Flutter: Is the file an image or not?

Issue

I want to load all the images that are in a given directory and exclude all files that are not images.

I don’t want to simply check for extensions because different conventions exist like ".jpg" and "jpeg" and because I don’t want to manually add new extensions if Flutter supports more image formats in the future. Also I want the user to be able to load image files even if they don’t have the correct extension-name.

How can I detect if a file is a (supported) image or not?

When Flutter tries to display a non-image file in the Image widget, it prints this error in the console: "Another exception was thrown: Exception: Invalid image data".
Unfortunatly this error seems to be only thown when Flutter is already building the widget, so trying to detect non-images during loading like this:

  void getFiles(path) async {
    //asyn function to get list of files
    var currentDir = Directory(path);

    files = [];

    await for (var entity
        in currentDir.list(recursive: false, followLinks: false)) {
      if (entity is File) {
        try {
          var image = Image(image: FileImage(entity));
          files.add(entity.path);
        } catch (e) {
          print(e);
        }
      }
    }
  }

dosn’t work.

The target plattform for the app is desktop, that is why I am not simply accessing the gallery.

Solution

You can make use of the mime package from the Dart team to extract the MIME types from file names:

import 'package:mime/mime.dart';

final mimeType = lookupMimeType('/some/path/to/file/file.jpg'); // 'image/jpeg'
Helper functions

If you want to know whether a file path represents an image, you can create a function like this:

import 'package:mime/mime.dart';

bool isImage(String path) {
  final mimeType = lookupMimeType(path);

  return mimeType.startsWith('image/');
}

Likewise, if you want to know if a path represents a document, you can write a function like this:

import 'package:mime/mime.dart';

bool isDocument(String path) {
  final mimeType = lookupMimeType(path);

  return mimeType == 'application/msword';
}

You can find lists of MIME types at IANA or look at the extension map in the mime package.

From file headers

With the mime package, you can even check against header bytes of a file:

final mimeType = lookupMimeType('image_without_extension', headerBytes: [0xFF, 0xD8]); // jpeg

Answered By – Tasnuva Tavasum oshin

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *