Skip to content

Novis\Image\Image::mime

Returns the MIME type of an image format, for example image/webp.

The argument is a Format. The result is a string you can send as a Content-Type header or store with the file. Each Format case has one MIME type:

  • Format::Jpeg gives image/jpeg, Format::Png gives image/png and Format::Webp gives image/webp.
  • Format::Gif gives image/gif, Format::Avif gives image/avif and Format::Jxl gives image/jxl.
  • Format::Svg gives image/svg+xml, and Format::Pdf gives application/pdf.

To find the type of an uploaded file, read its format with Image::info and pass $info->format to mime. The type then comes from the bytes of the file. A file name can be wrong, so it is not used.

mime reads no file and never throws an error.

Parameters

  • $formatFormat

Return value

Returns string.

Examples

Content type of an upload

<?nvs
use Novis\Image\Color;
use Novis\Image\Format;
// Shows how to find the `Content-Type` of an uploaded image from its bytes.
use Novis\Image\Image;
// These PNG bytes replace a file that a user uploaded.
tainted bytes $upload = Image::create(40, 20, Color::hex('#336699'))->withFormat(Format::Png)->encode();
// `Image::info` reads the format. This prints Content-Type: image/png.
var $info = Image::info($upload);
echo 'Content-Type: ', Image::mime($info->format), "\n";
Output
Content-Type: image/png

Every format

<?nvs
use Novis\Image\Format;
// Shows the MIME type of every image format.
use Novis\Image\Image;
array<Format> $formats = [
Format::Jpeg,
Format::Png,
Format::Webp,
Format::Gif,
Format::Avif,
Format::Jxl,
Format::Svg,
Format::Pdf,
];
// This prints one MIME type on each line, from image/jpeg to application/pdf.
foreach ($formats as Format $format) {
echo Image::mime($format), "\n";
}
Output
image/jpeg
image/png
image/webp
image/gif
image/avif
image/jxl
image/svg+xml
application/pdf

Allow some types

<?nvs
use Novis\Image\Color;
use Novis\Image\Format;
// Shows how to accept only some types of image, using their MIME types.
use Novis\Image\Image;
class Upload
{
public static function accepted(tainted bytes $upload): bool
{
string $type = Image::mime(Image::info($upload)->format);
// The site accepts JPEG and WebP photos. Every other type returns false.
return match ($type) {
'image/jpeg', 'image/webp' => true,
default => false,
};
}
}
Image $photo = Image::create(16, 16, Color::hex('#cc6633'));
// This prints true for the WebP file and false for the GIF file.
echo Upload::accepted($photo->withFormat(Format::Webp)->encode()) ? 'true' : 'false', "\n";
echo Upload::accepted($photo->withFormat(Format::Gif)->encode()) ? 'true' : 'false', "\n";
Output
true
false