如果您只处理图像并且需要 MIME 类型(例如用于标头),那么这是一种快速可靠的技术
<?php
$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));
?>
即使您重命名图像文件,它也会输出正确的图像 MIME 类型。
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
image_type_to_mime_type — 获取 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 返回的图像类型的 MIME 类型
image_type_to_mime_type() 函数将确定 IMAGETYPE 常量的 MIME 类型。
image_type
其中一个 IMAGETYPE_XXX
常量。
返回值如下
image_type |
返回值 |
---|---|
IMAGETYPE_GIF |
image/gif |
IMAGETYPE_JPEG |
image/jpeg |
IMAGETYPE_PNG |
image/png |
IMAGETYPE_SWF |
application/x-shockwave-flash |
IMAGETYPE_PSD |
image/psd |
IMAGETYPE_BMP |
image/bmp |
IMAGETYPE_TIFF_II (intel 字节顺序) |
image/tiff |
IMAGETYPE_TIFF_MM (motorola 字节顺序) |
image/tiff |
IMAGETYPE_JPC |
application/octet-stream |
IMAGETYPE_JP2 |
image/jp2 |
IMAGETYPE_JPX |
application/octet-stream |
IMAGETYPE_JB2 |
application/octet-stream |
IMAGETYPE_SWC |
application/x-shockwave-flash |
IMAGETYPE_IFF |
image/iff |
IMAGETYPE_WBMP |
image/vnd.wap.wbmp |
IMAGETYPE_XBM |
image/xbm |
IMAGETYPE_ICO |
image/vnd.microsoft.icon |
IMAGETYPE_WEBP |
image/webp |
IMAGETYPE_AVIF |
image/avif |
示例 #1 image_type_to_mime_type() 示例
<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>
注意:
此函数不需要 GD 图像库。
如果您只处理图像并且需要 MIME 类型(例如用于标头),那么这是一种快速可靠的技术
<?php
$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));
?>
即使您重命名图像文件,它也会输出正确的图像 MIME 类型。
我正在寻找检测图像格式的方法,我不确定这是否是最好的方法,但它对我有用。
<?php
$filename = 'http://static.php.net/www.php.net/images/php.gif';
$size = getimagesize($filename);
switch ($size['mime']) {
case "image/gif":
echo "Image is a gif";
break;
case "image/jpeg":
echo "Image is a jpeg";
break;
case "image/png":
echo "Image is a png";
break;
case "image/bmp":
echo "Image is a bmp";
break;
}
?>
将图像类型枚举映射到文件扩展名
$extensions = array(
IMAGETYPE_GIF => "gif",
IMAGETYPE_JPEG => "jpg",
IMAGETYPE_PNG => "png",
IMAGETYPE_SWF => "swf",
IMAGETYPE_PSD => "psd",
IMAGETYPE_BMP => "bmp",
IMAGETYPE_TIFF_II => "tiff",
IMAGETYPE_TIFF_MM => "tiff",
IMAGETYPE_JPC => "jpc",
IMAGETYPE_JP2 => "jp2",
IMAGETYPE_JPX => "jpx",
IMAGETYPE_JB2 => "jb2",
IMAGETYPE_SWC => "swc",
IMAGETYPE_IFF => "iff",
IMAGETYPE_WBMP => "wbmp",
IMAGETYPE_XBM => "xbm",
IMAGETYPE_ICO => "ico"
);