【发布时间】:2010-09-16 09:45:02
【问题描述】:
我正在寻找一种方法来获取当前放置在临时位置(例如:/tmp/jkhjkh78)的用户上传的图像,并从中创建一个 php 图像,自动检测格式。
有没有比使用 imagefromjpeg、imagefrompng 等进行尝试/捕捉更聪明的方法?
【问题讨论】:
我正在寻找一种方法来获取当前放置在临时位置(例如:/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 图片。'; }
【讨论】:
end(explode($image_file, ".")) 将是一种更聪明的方法,因为您可以处理任意长度的扩展。最后,使用 try/catch 实际上稍微安全一点,因为由于某种原因具有执行但没有写入权限的人可以上传伪装成图像的脚本然后执行它。但这可能是一个愚蠢的边缘案例 :) 我不确定,但getimagesize() 也可能会阻止这个问题。
人们推荐使用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
但是,官方文档页面上的 cmets 警告说,也不应该依赖它来进行验证。
【讨论】: