0

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

2
  • 1
    You could try appending 2>&1 to the end of your command to convert standard error to standard out and echo out compressed_jpg_content to see that error for debugging. Try $compressed_jpg_content = shell_exec("gm mogrify -quality 85 - < .escapeshellarg($image_path)." $filename.jpg 2>&1"); echo $compressed_jpg_content; Commented Jun 7, 2016 at 18:02
  • @AllenButler check edit Commented Jun 7, 2016 at 18:25

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Option b worked fine.How will the command change if $image_path is a BMP and i want to convert it to jpg
You have to use the -format option to set to jpg. Mogrify will then output to the same filename where the .bmp file extension.is replaced by .jpg.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.