PHP中的自动图像格式检测

时间:2008-10-09 22:09:52

标签: php image format jpeg

我正在寻找一种方法来获取用户上传的图像,该图像当前放在临时位置ex:/ tmp / jkhjkh78并从中创建一个php图像,自动检测格式。

有没有比使用imagefromjpeg,imagefrompng等尝试/捕捉更聪明的方法呢?

7 个答案:

答案 0 :(得分:26)

这是getimagesize的功能之一。他们可能应该称之为“getimageinfo”,但那是你的PHP。

答案 1 :(得分:5)

   //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

这将使图像名称看起来很酷且独特

答案 2 :(得分:3)

如果可用,请使用exif_imagetype() ..:

http://www.php.net/manual/en/function.exif-imagetype.php

我很确定默认情况下exif函数是可用的(即你必须专门排除它们而不是专门包含它们),当你安装php时

答案 3 :(得分:2)

您可以尝试finfo_file(),显然是mime_content_type()的改进版本。

编辑:好的,getimagesize()更好..

答案 4 :(得分:0)

如果您愿意,可以调用系统命令(如果您在linux / unix下),file

kender@eira:~$ file a
a: JPEG image data, EXIF standard 2.2

答案 5 :(得分:0)

这将帮助您了解扩展以及基于条件的结果

  

$ image_file ='http://foo.com/images.gif';
  $ extension = substr($ image_file,-4);
if($ extension ==“.jpg”){echo'它是JPG图像。'; } else {echo'它不是JPG图像。'; }

答案 6 :(得分:0)

人们建议使用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/htmlimage/gifapplication/vnd.ms-excel

然而,官方文档页面上的评论警告说,这不应该依赖于验证。

相关问题