简体   繁体   English

使用shell_exec()保存图像-使用imagejpeg和jpegoptim,以及stdin / stdinout

[英]Saving an image with shell_exec() - using imagejpeg & jpegoptim, with stdin / stdinout

I'm saving an image twice, once when I create it with imagejpeg and then I compress and overwrite with jpegoptim. 我将图像保存两次,一次是使用imagejpeg创建图像,然后使用jpegoptim压缩并覆盖。 How may I do this in one swoop, so I'm not saving the image twice? 一口气怎么做,这样就不会保存图像两次了?

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

Jpegoptim have stdin and stdout , but I'm struggling to understand how to use them. Jpegoptim具有stdin和stdout ,但是我正在努力了解如何使用它们。

I want to save the image with the shell, so I imagine something like this: 我想用外壳保存图像,所以我想像这样:

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

But alas, it doesn't work how I imagined. 但可惜的是,这与我的想象不符。

Although that might not perform better, this is a solution that writes nothing but the final result to disk: 尽管这可能不会更好,但是这是一种只将最终结果写入磁盘的解决方案:

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

Don't forget to close all handles afterwards if your script keeps running. 如果脚本继续运行,不要忘了之后关闭所有句柄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM