2015-06-21 49 views
1

我保存圖像兩次,一次使用imagejpeg創建圖像,然後壓縮並用jpegoptim覆蓋。我怎麼可以一次完成這個操作,所以我不會將圖像保存兩次?使用shell_exec()保存圖像 - 使用imagejpeg&jpegoptim,使用stdin/stdinout

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

Jpegoptim有stdin and stdout,但我努力理解如何使用它們。

我想將圖像保存與外殼,所以我想是這樣的:

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

但很可惜,它不工作,我如何可想而知。

+1

你確實需要一個管道:['popen'](http://php.net/popen)。因爲'imagejpeg'和'shell_exec'不會因爲它們被相互寫入而共享任何東西。 – mario

回答

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

不要忘記關閉所有處理之後,如果你的腳本保持運行。