我正在寻找一种方法来获取当前放置在临时位置的用户上传的图像,例如:/tmp/jkhjkh78,并从中创建一个 php 图像,自动检测格式。
有没有比使用 imagefromjpeg、imagefrompng 等进行尝试/捕捉更聪明的方法?
这是getimagesize的功能之一。他们可能应该称它为“getimageinfo”,但那是你的 PHP。
//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
这将使图像名称看起来很酷且独特
exif_imagetype()
如果可用,请使用.. :
http://www.php.net/manual/en/function.exif-imagetype.php
我很确定 exif 函数在安装 php 时默认可用(即您必须专门排除它们而不是专门包含它们)
你可以试试finfo_file()
,显然是mime_content_type()
.
编辑:好的,getimagesize()
更好..
如果您愿意,可以调用系统命令(如果您在 linux/unix 下)file
:
kender@eira:~$ file a
a: JPEG image data, EXIF standard 2.2
这将帮助您了解扩展以及基于条件的结果
$image_file = ' http://foo.com/images.gif ';
$extension = substr($image_file, -4);
if($extension == ".jpg"){ echo '这是一张 JPG 图片。'; } else { echo '它不是 JPG 图片。'; }
人们推荐使用getimagesize()
,但文档内容如下:
注意此函数要求文件名是有效的图像文件。如果提供了非图像文件,它可能会被错误地检测为图像并且函数将成功返回,但数组可能包含无意义的值。
不要
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
但是,官方文档页面上的评论警告说,也不应该依赖它来进行验证。