首页 > 解决方案 > HTML 和 PHP 表单 - 在多个图像上运行 imagemagick 命令

问题描述

我目前在页面上设置了一个表单,允许您上传文件,然后它将运行我在文件上创建的 imagemagick 命令并输出它。我希望此表单能够处理多个图像(或本地目录中的所有图像)。

我目前有我的 form.php:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
  <title>Image Framer </title>
</head>
<body>
  <?php
    if (isset($_SESSION['message']) && $_SESSION['message'])
    {
      printf('<p><b>%s</b></p>', $_SESSION['message']);
      unset($_SESSION['message']);
    }

    if (isset($_SESSION['final_file']) && $_SESSION['final_file'])
    {
      // printf('<b>%s</b>', $_SESSION['source_image']);
      // printf('<img src=%s />', $_SESSION['source_image']);
      // printf('<b>%s</b>', $_SESSION['final_file']);
      printf('<img src=%s />', $_SESSION['final_file']);
      echo "<br />";
      unset($_SESSION['source_image']);
      unset($_SESSION['final_file']);
    }
  ?>
  <form method="POST" action="process.php" enctype="multipart/form-data">
    <br />
    <div>
      <span>Upload an image to frame:</span>
      <input type="file" name="uploadedFile" />
    </div>

    <input type="submit" name="uploadBtn" value="Upload" />
  </form>
</body>
</html>

...我的进程.php:

<?php
session_start();

require_once 'process-lib.php';
$imageProcessor = new ImageProcessor();

$message = '';
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload')
{
  if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK)
  {
    // get details of the uploaded file
    $fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
    $fileName = $_FILES['uploadedFile']['name'];
    $fileSize = $_FILES['uploadedFile']['size'];
    $fileType = $_FILES['uploadedFile']['type'];
    $fileNameCmps = explode(".", $fileName);
    $fileExtension = strtolower(end($fileNameCmps));

    // sanitize file-name
    $newFileName = md5(time() . $fileName) . '.' . $fileExtension;

    // check if file has one of the following extensions
    $allowedfileExtensions = array('jpg', 'gif', 'png', 'jpeg');

    if (in_array($fileExtension, $allowedfileExtensions))
    {
      // directory in which the uploaded file will be moved
      $uploadFileDir = './uploaded_files/';
      $dest_path = $uploadFileDir . $newFileName;

      if(move_uploaded_file($fileTmpPath, $dest_path))
      {
        $message ='File is successfully uploaded.';
        $imageProcessor->convert($dest_path);
      }
      else
      {
        $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
      }
    }
    else
    {
      $message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions);
    }
  }
  else
  {
    $message = 'There is some error in the file upload. Please check the following error.<br>';
    $message .= 'Error:' . $_FILES['uploadedFile']['error'];
  }
}
$_SESSION['message'] = $message;
header("Location: form.php");

最后是我的 process-lib.php(包含一个图像处理器类):

<?php

class ImageProcessor {
  private $upload_dir;
  private $main_file;
  private $temp_background_file;
  private $background_file;
  private $final_file;

  public function __construct () {
    $this->upload_dir = 'uploaded_files';
    $this->main_file = $this->upload_dir . '/main.png';
    $this->temp_background_file = $this->upload_dir . '/temp_background.png';
    $this->background_file = $this->upload_dir . '/background.png';
    $this->final_file = $this->upload_dir . '/final.png';
  }

  public function convert ($source_image) {
    $_SESSION['source_image'] = $source_image;
    $_SESSION['final_file'] = $this->final_file;
    $exec = "convert " . $source_image . " -resize '500x500>' -write mpr:img0 \
    -set option:distort:viewport '%[fx:max(w,h)]x%[fx:max(w,h)]' \
    -distort SRT '%[fx:(w>h)*(w/2)],%[fx:(h>w)*(h/2)] %[fx:max(w/h,h/w)] 0' \
    -fill white -colorize 70 mpr:img0 -gravity center -composite " . $this->final_file;
    $output = `$exec`;
  }

  public function logger ($message) {
    file_put_contents('uploader.log', $message);
  }
}

我是 PHP 新手,大部分代码来自我找到的教程。我正在努力弄清楚如何处理多个图像。理想情况下,它会在输出时将“_T”附加到每个输入文件的名称。多张图片是刚刚上传到上传目录还是全部压缩都没有关系。

标签: phphtmlformsimagemagick

解决方案


我建议您使用 PHP ImageMagick 命令,而不是通过您的脚本运行命令。

一个典型的命令是

$im = new Imagick();

  // Convert image into Imagick
  $im->readimageblob($image);

  // Create thumbnail max of 200x82
  $im->thumbnailImage(200,82,true);

当然,它允许您在各种 ImageMagick 操作上处理多个文件。

您可以参考此链接了解详情:

https://www.php.net/manual/en/book.imagick.php

旁注:在 Linux 或 Windows 机器上安装 ImageMagick 模块非常简单。


推荐阅读