当前位置:首页> 正文

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

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

Fastest way to determine image resolution and file type in PHP or Unix command line?

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

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

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

编辑:解决方案可以是一个由 PHP 调用的命令行工具 UNIX,很像我现在使用 ImageMagick 的方式


如果你使用支持 GD 的 PHP,你可以试试 getimagesize()。


你试过了吗

1
identify -ping filename.png

?


抱歉,我无法将此作为评论添加到先前的答案,但我没有代表。进行一些快速而肮脏的测试,我还发现 exec("identify -ping... 比没有 -ping 时快 20 倍左右。但 getimagesize() 似乎仍然快 200 倍左右。

所以我会说 getimagesize() 是更快的方法。我只测试了 jpg 而不是 png.

测试只是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$files = array('2819547919_db7466149b_o_d.webp', 'GP1-green2.webp', 'aegeri-lake-switzerland.JPG');
foreach($files as $file){
  $size2 = array();
  $size3 = array();
  $time1 = microtime();
  $size = getimagesize($file);
  $time1 = microtime() - $time1;
  print"$time1 \
"
;
  $time2 = microtime();
  exec("identify -ping $file", $size2);
  $time2 = microtime() - $time2;
  print $time2/$time1 ."\
"
;
  $time2 = microtime();
  exec("identify $file", $size3);
  $time2 = microtime() - $time2;
  print $time2/$time1 ."\
"
;
  print_r($size);
  print_r($size2);
  print_r($size3);
}

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

您也可以使用 mime_content_type() 来获取 MIME 类型。


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

为此,您可以使用 'file' unix 命令(或者实现相同功能的一些 php 函数)。

/tmp$ file stackoverflow-logo-250.webp
stackoverflow-logo-250.webp: PNG image data, 250 x 70, 8-bit colormap, non-interlaced


exif_imagetype() 比 getimagesize() 快。

$filename ="一些文件";
$data = exif_imagetype($filename);
回声"前";
打印_r($数据);
回声"/前";

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
        )
)

如果您使用的是 PHP,我建议您使用 Imagick 库而不是调用 exec()。您正在寻找的功能是 Imagick::pingImage().


展开全文阅读

相关内容