WordPress at a glance

wp_get_image_mime() WP 4.7.1

Gets the real MIME type of an image file.

We can't trust to the image type in the image name, for example png image can be called image.jpg.

PHP functions are used to accurately determine mime:

✈ 1 time = 0.135771s = extreme slow | 50000 times = 176.48s = extreme slow PHP 7.1.11, WP 4.9.4

No Hooks.

Return

String/false. The actual mime type or false if the type cannot be determined.

Usage

wp_get_image_mime( $file );
$file(string) (required)
Full path to the file.

Examples

#1 Get the mime type of the image in the template files (screenshot of the theme)

$screenshot_path = get_template_directory() . '/screenshot.png';
echo wp_get_image_mime( $screenshot_path );
//> image/png

Code of wp_get_image_mime: wp-includes/functions.php VER 4.9.8

<?php
function wp_get_image_mime( $file ) {
	/*
	 * Use exif_imagetype() to check the mimetype if available or fall back to
	 * getimagesize() if exif isn't avaialbe. If either function throws an Exception
	 * we assume the file could not be validated.
	 */
	try {
		if ( is_callable( 'exif_imagetype' ) ) {
			$imagetype = exif_imagetype( $file );
			$mime = ( $imagetype ) ? image_type_to_mime_type( $imagetype ) : false;
		} elseif ( function_exists( 'getimagesize' ) ) {
			$imagesize = getimagesize( $file );
			$mime = ( isset( $imagesize['mime'] ) ) ? $imagesize['mime'] : false;
		} else {
			$mime = false;
		}
	} catch ( Exception $e ) {
		$mime = false;
	}

	return $mime;
}

Related Functions

From tag: MIME type

More from category: Images

No comments
    Hello, !     Log In . Register