我正在寻找一种方法来获取当前放置在临时位置的用户上传图像,例如/ tmp/jkhjkh78,并从中创建一个php图像,自动检测格式。PHP中的自动图像格式检测
有没有一个更聪明的方法来做到这一点比一堆尝试/捕捉imagefromjpeg,imagefrompng等?
我正在寻找一种方法来获取当前放置在临时位置的用户上传图像,例如/ tmp/jkhjkh78,并从中创建一个php图像,自动检测格式。PHP中的自动图像格式检测
有没有一个更聪明的方法来做到这一点比一堆尝试/捕捉imagefromjpeg,imagefrompng等?
可以调用系统命令(如果你在Linux/UNIX),file
如果你喜欢:
[email protected]:~$ file a
a: JPEG image data, EXIF standard 2.2
这是的getimagesize的功能之一。他们可能应该把它称为“getimageinfo”,但这是你的PHP。
你可以试试finfo_file(),显然是mime_content_type()的改进版本。
编辑:OK,和getimagesize()是更好的..
使用exif_imagetype()(如果可用)..:
http://www.php.net/manual/en/function.exif-imagetype.php
我敢肯定的EXIF功能可以用默认值(即你必须明确排除他们,而不是专门包括他们)当你安装php
这将帮助你知道的扩展以及根据条件的结果
$ image_file ='http://foo.com/images.gif';
$ extension = substr($ image_file,-4);
if($ extension ==“.jpg”){echo'它是一张JPG图片。'; } else {echo'它不是JPG图片。'; }
//Image Processing
$cover = $_FILES['cover']['name'];
$cover_tmp_name = $_FILES['cover']['tmp_name'];
$cover_img_path = '/images/';
$type = exif_imagetype($cover_tmp_name);
if ($type == (IMAGETYPE_PNG || IMAGETYPE_JPEG || IMAGETYPE_GIF || IMAGETYPE_BMP)) {
$cover_pre_name = md5($cover); //Just to make a image name random and cool :D
/**
* @description : possible exif_imagetype() return values in $type
* 1 - gif image
* 2 - jpg image
* 3 - png image
* 6 - bmp image
*/
switch ($type) { #There are more type you can choose. Take a look in php manual -> http://www.php.net/manual/en/function.exif-imagetype.php
case '1' :
$cover_format = 'gif';
break;
case '2' :
$cover_format = 'jpg';
break;
case '3' :
$cover_format = 'png';
break;
case '6' :
$cover_format = 'bmp';
break;
default :
die('There is an error processing the image -> please try again with a new image');
break;
}
$cover_name = $cover_pre_name . '.' . $cover_format;
//Checks whether the uploaded file exist or not
if (file_exists($cover_img_path . $cover_name)) {
$extra = 1;
while (file_exists($cover_img_path . $cover_name)) {
$cover_name = md5($cover) . $extra . '.' . $cover_format;
$extra++;
}
}
//Image Processing Ends
这会使图像的名字看起来很酷,独特
人们使用getimagesize()
but the documentation阅读推荐:
注意该函数要求文件名是一个有效的图像文件。如果提供了 非图像文件,则可能会错误地将其检测为图像 ,并且该函数将成功返回,但该数组可能包含 无意义的值。
请勿使用
getimagesize()
来检查给定文件是否为有效图像。 改用专用解决方案,例如Fileinfo扩展。
在Fileinfo的扩展相关的功能是finfo_file()
:
string finfo_file (resource $finfo , string $file_name = NULL
[, int $options = FILEINFO_NONE [, resource $context = NULL ]])
返回的
file_name
论证内容的文字说明,或FALSE如果发生错误。
给出的示例返回值是:text/html
,image/gif
,application/vnd.ms-excel
然而,官方文档页面的评论警告说,这不应该被用于验证要么依靠。
首先,没有检查扩展名为jpeg,jpe,jif和jfif。虽然不常见,但它们仍然被一些人使用(但大多数情况下是jpeg)。此外,扩展名不一定反映图像格式,并且如果网站容易受到本地文件包含,则上传带有JPG扩展名的PHP文件可能是致命的。 – 2014-02-03 18:25:11