Save shell output to variable

怎甘沉沦 提交于 2019-12-25 07:18:46

问题


I am trying to compress a jpg with mogrify (GraphicsMagicks) and i need to store the result in a variable.

$compressed_jpg_content = shell_exec("gm mogrify -quality 85 - < ".escapeshellarg($image_path)." $filename.jpg");
    if (!$compressed_jpg_content) {
        throw new Exception("Conversion to compressed JPG failed");
    }

However its not working and i get Conversion to compressed JPG failed and i think there is a problem with my command

Edit

Thanks to Allen Butler

In this case $image_path is actually a POST variable and $filename is I4tWX0HI.jpg

Error : gm mogrify: Unable to open file (I4tWX0HI.jpg)

The error is pretty obvious since I4tWX0HI.jpg does not exist yet.That being said , how can i modify the command to make it put the content in the variable instead of trying to open a file

Regards


回答1:


According to the gm mogrify manual, if overwrites the original file with the new image so you can not specify the target image on the command line.

You can try one of the following options:

1) Hope that if mogrify ready from STDIN, it will output to STDOUT. Can not test it so it is a guest. You will notice that you skip the output file in that case:

$compressed_jpg_content = shell_exec("gm mogrify -quality 85 - < ".escapeshellarg($image_path));

b) Let mogrify change the image (ignore the filename you have) and read the image data afterwards:

$compressed_jpg_content = shell_exec("gm mogrify -quality 85 ".escapeshellarg($image_path)." && cat ".escapeshellarg($image_path));

c) If you don't want to change the original file, copy it before:

$tmpfile = tempnam(sys_get_temp_dir(), "image_");
copy($image, $tmpfile);
shell_exec("gm mogrify -quality 85 ".escapeshellarg(tmpfile));
$compressed_jpg_content = file_get_contents($tmpfile);
unlink($tmpfile);


来源:https://stackoverflow.com/questions/37685871/save-shell-output-to-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!