PHP 代码,用于将图像格式更改为 JPG


PHP code to change image format to JPG

我构造了这个PHP代码来使用ImageMagick将gif文件转换为jpg,但它似乎不起作用。也许我错过了一些东西:

<?php
$cwd = getcwd();
$directory = 'temp_images/input/'; // add path to the source direcotry, reprocesses all images directly, not fancy.
$dh = opendir($directory);
while($file = readdir($dh)) {
  if (strlen($file) > 2) {
    $dirfiles[]=$file;
  }
}
closedir($dh);
reset($dirfiles);
asort($dirfiles);

set_time_limit(0);
foreach ($dirfiles as $dirfile) {
  $file = $directory.$dirfile;
  $cmd = 'mogrify -format jpg *.gif $file';     
  echo  $dirfile . " mogrified to JPG 'n";
}
?>

gif 文件未转换。

更新:在我自己的代码中,我替换为 $cmd = 'mogrify -format jpg *.gif $file'; exec("mogrify -format jpg .$file");

当我使用mogrify时,我的印象是原始文件被清除。我该怎么做?

您使用了错误类型的"引号"

foreach ($dirfiles as $dirfile) {
  $file = $directory.$dirfile;
  $cmd = 'mogrify -format jpg *.gif $file';     
  echo  $dirfile . " mogrified to JPG 'n";
}

您需要反引号运算符。

foreach ($dirfiles as $dirfile) {
  $file = $directory.$dirfile;
  $cmdResult = `mogrify -format jpg *.gif $file`;     
  echo  $dirfile . " mogrified to JPG 'n";
}

这与使用shell_exec相同。

foreach ($dirfiles as $dirfile) {
  $file = $directory.$dirfile;
  $cmdResult = shell_exec ( "mogrify -format jpg *.gif {$file}" );     
  echo  $dirfile . " mogrified to JPG 'n";
}

$cmd永远不会执行...它只是一个字符串值。