Home > Net >  Can't Use ImageMagick (convert) command in PHP
Can't Use ImageMagick (convert) command in PHP

Time:04-08


I want to edit images using ImageMagick and PHP on my website.
I'm on Linux (Raspbian OS) and have PHP and ImageMagick installed.
I'm trying to do something similar to: `convert test.png test.webp` using PHP. All work in the Terminal.

What I've tried:

putenv("PATH=/usr/local/bin:/usr/bin:/bin");
Full command path "/usr/bin/convert test.png test.webp" (Work in Terminal)
All of the PHP CMD commands including: exec() shell_exec() system() passthru()
(All of the output of those were empty, but simple commands like echo $PWD worked)
Images Full Path "convert /home/pi/www/test.png /home/pi/www/test.webp" (And all of the above variations)

Any help in hugely appreciated!

CodePudding user response:

Use 2>&1 in php shell_exec command and try this code;

$file = "/home/pi/www/test.png";
$dest = "/home/pi/www/test.webp";

$file_extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if(extension_loaded("cwebp") || extension_loaded('gif2webp')) {
  if($file_extension=="png" or $file_extension=="jpg" or $file_extension=="jpeg"){
    shell_exec("cwebp -q 80 ".escapeshellarg($file)." -o ".escapeshellarg($dest) . " 2>&1");
  }
  if($file_extension=="gif"){
    shell_exec("gif2webp -q 80 ".escapeshellarg($file)." -o ".escapeshellarg($dest) . " 2>&1");
  }
} else if(extension_loaded("gmagick") || extension_loaded('imagick')) {
  if($file_extension=="png" or $file_extension=="jpg" or $file_extension=="jpeg" or $file_extension=="gif"){
    shell_exec("convert ".escapeshellarg($file)." -quality 80 -define webp:lossless=true ".escapeshellarg($dest) . " 2>&1");
  }
} else {
  die("Does not have any webp library!");
}

I don't know your version of Imagick, some arguments may vary by version, but it might give some idea for your code.

CodePudding user response:

You have also an imagick extension in PHP: https://www.php.net/manual/fr/book.imagick.php

  • Related