php 获取图片扩展

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14746518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:54:15  来源:igfitidea点击:

Get image extension

phpimage

提问by Oto Shavadze

I want get uploaded image extension.

我想要上传图片扩展名。

As I know, best way is getimagesize()function.

据我所知,最好的方法是getimagesize()功能。

but this function's mime, returns image/jpegwhen image has .jpgor also .JPEGextension.

但是这个函数的 mime,image/jpeg当图像有.jpg或也有.JPEG扩展时返回。

How can get exactly extension?

怎样才能得到准确的扩展?

回答by lupatus

you can use image_type_to_extensionfunction with image type returned by getimagesize:

您可以使用image_type_to_extension具有以下图像类型的函数getimagesize

$info = getimagesize($path);
$extension = image_type_to_extension($info[2]);

回答by phpalix

$ext = pathinfo($filename, PATHINFO_EXTENSION);

回答by vasudev

You can also use strrpos and substr functions to get extension of any file

您还可以使用 strrpos 和 substr 函数来获取任何文件的扩展名

$filePath="images/ajax-loader.gif";

$type=substr($filePath,strrpos($filePath,'.')+1);

echo "file type=".$type;

output: gif

输出:gif

if you want extension like .gif

如果你想要像 .gif 这样的扩展名

$type=substr($filePath,strrpos($filePath,'.')+0);

output: .gif

输出:.gif

回答by Devang Rathod

$image = explode(".","test.file.hhh.kkk.jpg");
echo end($image);

回答by dfsq

One more way to do it:

另一种方法:

$ext = strrchr($filename, "."); // .jpg

回答by Siki

You can also explode the file name with dots and take the end of the array as follows:

你也可以用点来分解文件名并取数组的末尾,如下所示:

$ext = end(explode('.', 'image.name.gif'));

According to: Two different ways to find file extension in PHP

根据:在 PHP 中查找文件扩展名的两种不同方式

And a new way for you lol:

还有一种新的方式给你哈哈:

$ext = explode('.', 'file.name.lol.lolz.jpg');
echo $ext[count($ext) - 1];

回答by 49volro

For those who want to check if image type is JPEG, PNG or etc. You can use exif_imagetypefunction. This function reads the first bytes of an image and checks its signature. Here is a simple example from php.net:

对于那些想要检查图像类型是否为 JPEG、PNG 等的人,您可以使用exif_imagetype函数。此函数读取图像的第一个字节并检查其签名。这是来自 php.net 的一个简单示例:

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
   echo 'The picture is not a gif';
}
?>

回答by eozzy

$size = getimagesize($filename);
$ext = explode('/', $size['mime'])[1];

回答by James

$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

or to make it clean

或者让它干净

$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);