在PHP或者Unix命令行中确定图像分辨率和文件类型的最快方法?

时间:2020-03-06 14:20:19  来源:igfitidea点击:

我目前正在使用ImageMagick来确定上传到网站的图像的大小。通过在命令行上调用ImageMagick的" identify",大约需要0.42秒才能确定1MB JPEG的尺寸以及它是JPEG的事实。我觉得有点慢。

使用Imagick PHP库的速度甚至更慢,因为它会在对图像进行任何处理之前尝试将整个1MB的内存加载到内存中(在这种情况下,只需确定其大小和类型)。

有什么解决方案可以加快确定任意图像文件具有哪种文件类型和尺寸的过程?我可以只支持JPEG和PNG。对我来说重要的是,文件类型是通过查看文件的标题而不是扩展名来确定的。

编辑:解决方案可以是PHP调用的命令行工具UNIX,非常类似于我目前使用ImageMagick的方式

解决方案

如果我们使用的是具有GD支持的PHP,则可以尝试getimagesize()。

It's important to me that the file type is determined by looking at the file's headers and not simply the extension.

为此,我们可以使用"文件" unix命令(或者实现相同功能的某些php函数)。

/ tmp $文件stackoverflow-logo-250.png
`stackoverflow-logo-250.png:PNG图像数据,250 x 70,8位色图,非隔行扫描

你有没有尝试过

identify -ping filename.png

实际上,要使用getimagesize(),不需要编译GD。

我们还可以使用mime_content_type()获取MIME类型。

抱歉,我无法将此添加为上一个答案的注释,但我没有代表。通过进行一些快速而肮脏的测试,我还发现exec(" identify -ping ..."的速度大约是不使用-ping的速度的20倍。但是getimagesize()似乎仍然快200倍。

所以我想说getimagesize()是更快的方法。我仅在jpg而非png上进行了测试。

测试只是

$files = array('2819547919_db7466149b_o_d.jpg', 'GP1-green2.jpg', 'aegeri-lake-switzerland.JPG');
foreach($files as $file){
  $size2 = array();
  $size3 = array();
  $time1 = microtime();
  $size = getimagesize($file);
  $time1 = microtime() - $time1;
  print "$time1 \n";
  $time2 = microtime();
  exec("identify -ping $file", $size2);
  $time2 = microtime() - $time2;
  print $time2/$time1 . "\n";
  $time2 = microtime();
  exec("identify $file", $size3);
  $time2 = microtime() - $time2;
  print $time2/$time1 . "\n";
  print_r($size);
  print_r($size2);
  print_r($size3);
}

exif_imagetype()比getimagesize()更快。

$ filename =" somefile";
$ data = exif_imagetype($ filename);
回声" <PRE>";
print_r($ data);
回声" </ PRE>";

输出:

Array (
        [FileName] => somefile
        [FileDateTime] => 1234895396
        [FileSize] => 15427
        [FileType] => 2
        [MimeType] => image/jpeg
        [SectionsFound] => 
        [COMPUTED] => Array
            (
                [html] => width="229" height="300"
                [Height] => 300
                [Width] => 229
                [IsColor] => 1
        )
)