【问题标题】:Uploaded image: converting format上传图片:转换格式
【发布时间】:2013-02-11 09:25:53
【问题描述】:

我想将上传的图像转换为其原始格式(jpg、jpeg rpng 等),但我需要将这些图像的大小重新调整为 150 像素宽和 210 像素高。复制时是否可以更改大小,还是必须转换它?

这不成功:

    $uploaddir1 = "/home/myweb/public_html/temp/sfds454.png";
    $uploaddir2 = "/home/myweb/public_html/images/sfds454.png";

    $cmd = "/usr/bin/ffmpeg -i $uploaddir1 -vframes 1 -s 150x210 -r 1 -f mjpeg $uploaddir2";
    @exec($cmd);

【问题讨论】:

    标签: php image imagemagick


    【解决方案1】:

    您可以使用 gd 代替 ffmpeg。要转换或调整图像大小,请参见以下示例:http://ryanfait.com/resources/php-image-resize/resize.txt

    gd 的 PHP 库:

    http://php.net/manual/en/function.imagecopyresampled.php

    该页面中还有一些调整脚本大小的示例。

    【讨论】:

      【解决方案2】:

      我最近不得不解决这个问题,并实现了这个简单的缓存解决方案:

      <?php
      function send($name, $ext) {
          $fp = fopen($name, 'rb');
          // send the right headers
          header("Content-Type: image/$ext");
          header("Content-Length: " . filesize($name));
      
          // dump the picture and stop the script
          fpassthru($fp);
          exit;
      }
      
      error_reporting(E_ALL);
      ini_set('display_errors', 'On');
      
      if (isset($_REQUEST['fp'])) {
          $ext = pathinfo($_REQUEST['fp'], PATHINFO_EXTENSION);
      
          $allowedExt = array('png', 'jpg', 'jpeg');
          if (!in_array($ext, $allowedExt)) {
              echo 'fail';
          }
      
          if (!isset($_REQUEST['w']) && !isset($_REQUEST['h'])) {
              send($_REQUEST['fp']);
          }
          else {
              $w = $_REQUEST['w'];
              $h = $_REQUEST['h'];
      
              //use height, width, modification time and path to generate a hash
              //that will become the file name
              $filePath = realpath($_REQUEST['fp']);
              $cachePath = md5($filePath.filemtime($filePath).$h.$w);
              if (!file_exists("tmp/$cachePath")) {
                  exec("gm convert -quality 80% -colorspace RGB -resize " .$w .'x' . $h . " $filePath tmp/$cachePath");
              }
              send("tmp/$cachePath", $ext);
      
          }
      }
      ?>
      

      我注意到的一些事情:

      1. Graphicsmagick 的转换速度比 imagemagick 快得多,尽管我没有使用 cuda 处理测试转换。
      2. 对于最终产品,我使用语言的本机图形库在 ASP 中重新实现了此代码。这又快了很多,但如果发生内存不足错误会中断(在我的工作站上运行良好,但在 4GB RAM 服务器上无法运行)。

      【讨论】:

        猜你喜欢
        • 2015-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-09
        • 1970-01-01
        相关资源
        最近更新 更多