Php 使用shell_exec()保存图像-使用imagejpeg&;jpegoptim,带标准输入/标准输出

Php 使用shell_exec()保存图像-使用imagejpeg&;jpegoptim,带标准输入/标准输出,php,shell-exec,jpegoptim,Php,Shell Exec,Jpegoptim,我保存了一个图像两次,一次是用imagejpeg创建的,然后用jpegoptim压缩和覆盖。我如何一下子做到这一点,这样我就不会保存图像两次了 $im = imagecreatefromstring($imageString); imagejpeg($im, 'img/test.jpg', 100); shell_exec("jpegoptim img/test.jpg"); Jpegoptim有,但我很难理解如何使用它们 我想用外壳保存图像,所以我想象如下: imagejpeg($im);

我保存了一个图像两次,一次是用imagejpeg创建的,然后用jpegoptim压缩和覆盖。我如何一下子做到这一点,这样我就不会保存图像两次了

$im = imagecreatefromstring($imageString);
imagejpeg($im, 'img/test.jpg', 100);
shell_exec("jpegoptim img/test.jpg");
Jpegoptim有,但我很难理解如何使用它们

我想用外壳保存图像,所以我想象如下:

imagejpeg($im);
shell_exec("jpegoptim --stdin > img/test.jpg");

但遗憾的是,它并没有像我想象的那样起作用。

尽管这可能不会表现得更好,但这是一种只将最终结果写入磁盘的解决方案:

// I'm not sure about that, as I don't have jpegoptim installed 
$cmd = "jpegoptim --stdin > img/test.jpg";
// Use output buffer to save the output of imagejpeg
ob_start(); 
imagejpeg($img, NULL, 100); 
imagedestroy($img); 
$img = ob_get_clean();
// $img now contains the binary data of the jpeg image
// start jpegoptim and get a handle to stdin 
$handle = popen($cmd, 'w');
// write the image to stdin
fwrite($handle, $img."\n");
如果脚本继续运行,不要忘记关闭所有句柄。

确实需要管道:。因为
imagejpeg
shell\u exec
不共享任何内容,因为它们是一个接一个地编写的。