rosell-dk/image-mime-type-sniffer

Sniff mime type (images only)

1.1.1 2022-04-20 14:31 UTC

This package is auto-updated.

Last update: 2024-11-06 18:13:36 UTC


README

Latest Stable Version Minimum PHP Version Build Status Software License Coverage Monthly Downloads Dependents

Gets mime type of common image files by sniffing the file content, looking for signatures.

The fact that this library limits its ambition to sniff images makes it light and simple. It is also quite fast. Most other sniffers iterates through all common signatures, however this library uses a mix of finite-state machine approach and iteration to achieve a good balance of speed, compactness, simplicity and readability.

The library recognizes the most widespread image formats, such as GIF, JPEG, WEBP, AVIF, JPEG-2000 and HEIC.

Usage

use \ImageMimeTypeSniffer\ImageMimeTypeSniffer;

$mimeType = ImageMimeTypeSniffer::detect($fileName);  
if (is_null($mimeType)) {
  // mimetype was not detected, which means the file is probably not an image (unless it is a rare type)
} else {
  // It is an image, and we know the mimeType
}

PS: An \Exception is thrown if the file is unreadable.

Platforms

Works on (at least): OS: Ubuntu (22.04, 20.04), Windows (2022, 2019), Mac OS (11, 10.15) PHP: 5.6 - 8.2 (also tested 8.3 and 8.4 development versions in October 2023)

Each new release will be tested on all combinations of OSs and PHP versions that are supported by GitHub-hosted runners. Except that we do not below PHP 5.6.

Testing consists of running the unit tests. The code in this library is almost completely covered by tests (~97% coverage).

Release 1.1.1 has been tested in PHP: 5.6 - 8.2 on the following OSs: Ubuntu (22.04, 20.04, 18.04), Windows (2022, 2019), Mac OS (13, 12, 11, 10.15). Code coverage: ~97%. For some reason PHP 5.6 testing fails on Windows

List of recognized image types:

  • application/psd
  • image/avif
  • image/bmp
  • image/gif
  • image/heic
  • image/jp2
  • image/jp20
  • image/jpeg
  • image/jpm
  • image/jpx
  • image/png
  • image/svg+xml
  • image/tiff
  • image/webp
  • image/x-icon
  • video/mj2

TODO: image/heif

Alternatives

I have created a library that uses this library as well as other methods (finfo, exif_imagetype, etc) for determining image type. You might want to use that instead, to cover all bases. It is available here: image-mime-type-guesser.

There are also other PHP mime type sniffers out there:

Do you like what I do?

Perhaps you want to support my work, so I can continue doing it :)