wp_get_image_mime() WordPress Function

The wp_get_image_mime() function is used to get the image mime type of a given image. This function can be used to verify that an image is of a certain type before performing any further actions on it.

wp_get_image_mime( string $file ) #

Returns the real mime type of an image file.


Description

This depends on exif_imagetype() or getimagesize() to determine real mime types.


Top ↑

Parameters

$file

(string)(Required)Full path to the file.


Top ↑

Return

(string|false) The actual mime type or false if the type cannot be determined.


Top ↑

Source

File: wp-includes/functions.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 available. 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' ) ) {
			// Don't silence errors when in debug mode, unless running unit tests.
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG
				&& ! defined( 'WP_RUN_CORE_TESTS' )
			) {
				// Not using wp_getimagesize() here to avoid an infinite loop.
				$imagesize = getimagesize( $file );
			} else {
				// phpcs:ignore WordPress.PHP.NoSilencedErrors
				$imagesize = @getimagesize( $file );
			}

			$mime = ( isset( $imagesize['mime'] ) ) ? $imagesize['mime'] : false;
		} else {
			$mime = false;
		}

		if ( false !== $mime ) {
			return $mime;
		}

		$magic = file_get_contents( $file, false, null, 0, 12 );

		if ( false === $magic ) {
			return false;
		}

		/*
		 * Add WebP fallback detection when image library doesn't support WebP.
		 * Note: detection values come from LibWebP, see
		 * https://github.com/webmproject/libwebp/blob/master/imageio/image_dec.c#L30
		 */
		$magic = bin2hex( $magic );
		if (
			// RIFF.
			( 0 === strpos( $magic, '52494646' ) ) &&
			// WEBP.
			( 16 === strpos( $magic, '57454250' ) )
		) {
			$mime = 'image/webp';
		}
	} catch ( Exception $e ) {
		$mime = false;
	}

	return $mime;
}


Top ↑

Changelog

Changelog
VersionDescription
5.8.0Added support for WebP images.
4.7.1Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More