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

622 views Asked by At

I'm saving an image twice, once when I create it with imagejpeg and then I compress and overwrite with 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.

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.

1

There are 1 answers

0
Johann Bauer On BEST ANSWER

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.