1

我保存了两次图像,一次是用 imagejpeg 创建它,然后用 jpegoptim 压缩和覆盖。我怎样才能一口气做到这一点,所以我不会两次保存图像?

$im = imagecreatefromstring($imageString);
imagejpeg($im, 'img/test.jpg', 100);
shell_exec("jpegoptim img/test.jpg");

Jpegoptim 有stdin 和 stdout,但我很难理解如何使用它们。

我想用外壳保存图像,所以我想像这样:

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

但很可惜,它并没有像我想象的那样工作。

4

1 回答 1

1

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

// 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");

如果您的脚本继续运行,请不要忘记在之后关闭所有句柄。

于 2015-06-21T19:46:02.813 回答