PHP:获取optipng的输出

时间:2018-03-09 14:52:21

标签: php

我使用jpegoptim和optipng来优化浏览器中调用的php脚本中的图像。我这样做:

    fun onReceived(anything: Anything) =
        when {
            anything === Anything.DEFAULT -> <TA DA!>
        }

这很好用并输出:

$s = exec('/myoptimizer/jpegoptim -m60 -o --strip-all /httpd/images/myimage.jpg');
print $s;

现在与optipng相同:

/httpd/images/myimage.jpg 600x90 24bit P JFIF [OK] 14572 --> 14542 bytes (0.21%), optimized. 

在控制台上执行相同的命令,我得到:

$s = exec('/myoptimizer/optipng -o7 -preserve -strip all /httpd/images/myimage.png /httpd/images/myimage.png', $aOutput, $ret);

var_dump($s);
var_dump($a);
var_dump($ret);

But:
$s is empty.
$a is empty array.
$ret is 0.

** Processing: /httpd/images/myimage.png
60x18 pixels, 4x8 bits/pixel, RGB+alpha
Input IDAT size = 2235 bytes
Input file size = 2292 bytes

Trying:
  zc = 9  zm = 9  zs = 0  f = 5         IDAT size = 2235
  zc = 9  zm = 8  zs = 0  f = 5         IDAT size = 2235
  zc = 8  zm = 9  zs = 0  f = 5         IDAT size = 2235
  zc = 8  zm = 8  zs = 0  f = 5         IDAT size = 2235

/httpd/images/myimage.png is already optimized.

作品。

如何在PHP中获取输出?我也尝试过shell_exec,passthru和system,但是:根本没有输出。

1 个答案:

答案 0 :(得分:1)

exec()方法的第二个参数捕获已执行命令的标准输出。在您的情况下,optipng不会将其结果输出到标准输出BUT到标准错误。您可以通过将2>&1添加到执行程序的末尾来将std错误消息重定向到std输出,在这种情况下,您的代码将如下所示:

<?php
$imagePath = '/httpd/images/myimage.png';
$comand    = '/myoptimizer/optipng -o7 -preserve -strip all';

exec("$command $imagePath 2>&1", $outout);

var_dump($output);