I'm using the package image_picker to accept an image from the user. This results in a PickedFile and byte array. Since the image is then uploaded I'm wondering how to guess the mime type from the byte array.

PickedFile image =
    await _picker.getImage(source: ImageSource.gallery, imageQuality: 50);
Uint8List data = await image.readAsBytes();


Solution 1: jamesdlin

package:mime has a lookupMimeType function that can infer the MIME type either from a file extension or from magic bytes in the content. As of writing, it should support detecting content for:

  • application/pdf
  • application/postscript
  • image/gif
  • image/jpeg
  • image/png
  • image/tiff
  • video/mp4
  • model/gltf-binary

(See https://github.com/dart-lang/mime/blob/master/lib/src/magic_number.dart for the current list of types it supports out of the box.)

Example:

final data = await image.readAsBytes();
final mime = lookupMimeType('', headerBytes: data);