質問

PHP で大きな画像のサイズを変更する最も効率的な方法は何ですか?

私が現在使用しているのは、 GD 関数 imagecopy リサンプリングして高解像度の画像を取得し、Web 表示用のサイズ (およそ幅 700 ピクセル、高さ 700 ピクセル) にきれいにサイズ変更します。

これは小さい (2 MB 未満) 写真にうまく機能し、サーバー上でのサイズ変更操作全体にかかる時間は 1 秒もかかりません。ただし、このサイトは最終的には、最大 10 MB のサイズの画像 (または最大 5000x4000 ピクセルの画像) をアップロードする可能性のある写真家にサービスを提供する予定です。

大きな画像に対してこの種のサイズ変更操作を実行すると、メモリ使用量が大幅に増加する傾向があります (画像が大きいと、スクリプトのメモリ使用量が 80 MB を超えて急増する可能性があります)。このサイズ変更操作をより効率的にする方法はありますか?次のような代替画像ライブラリを使用する必要がありますか? イメージマジック?

現在、サイズ変更コードは次のようになります

function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
    // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
    // and places it at endfile (path/to/thumb.jpg).

    // Load image and get image size.
    $img = imagecreatefromjpeg($sourcefile);
    $width = imagesx( $img );
    $height = imagesy( $img );

    if ($width > $height) {
        $newwidth = $thumbwidth;
        $divisor = $width / $thumbwidth;
        $newheight = floor( $height / $divisor);
    } else {
        $newheight = $thumbheight;
        $divisor = $height / $thumbheight;
        $newwidth = floor( $width / $divisor );
    }

    // Create a new temporary image.
    $tmpimg = imagecreatetruecolor( $newwidth, $newheight );

    // Copy and resize old image into new image.
    imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );

    // Save thumbnail into a file.
    imagejpeg( $tmpimg, $endfile, $quality);

    // release the memory
    imagedestroy($tmpimg);
    imagedestroy($img);
役に立ちましたか?

解決

ImageMagick の方がはるかに速いと言われています。せいぜい、両方のライブラリを比較してそれを測定するだけです。

  1. 代表的な画像を1000枚用意します。
  2. 2つのスクリプトを作成します。1つはGD用、もう1つはImageMagick用です。
  3. 両方を数回実行します。
  4. 結果を比較します(総実行時間、CPUおよびI/Oの使用、結果の画質)。

他の人にとって最高のものでも、あなたにとって最高のものであるはずはありません。

また、私の意見では、ImageMagick の API インターフェイスははるかに優れています。

他のヒント

以下は、私がプロジェクトで使用した、正常に動作する php.net ドキュメントのスニペットです。

<?
function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
    // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.
    // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled".
    // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.
    // Author: Tim Eckel - Date: 09/07/07 - Version: 1.1 - Project: FreeRingers.net - Freely distributable - These comments must remain.
    //
    // Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. Must be greater than zero.
    // Between 0 and 1 = Fast, but mosaic results, closer to 0 increases the mosaic effect.
    // 1 = Up to 350 times faster. Poor results, looks very similar to imagecopyresized.
    // 2 = Up to 95 times faster.  Images appear a little sharp, some prefer this over a quality of 3.
    // 3 = Up to 60 times faster.  Will give high quality smooth results very close to imagecopyresampled, just faster.
    // 4 = Up to 25 times faster.  Almost identical to imagecopyresampled for most images.
    // 5 = No speedup. Just uses imagecopyresampled, no advantage over imagecopyresampled.

    if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; }
    if ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {
        $temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1);
        imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h);
        imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality);
        imagedestroy ($temp);
    } else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    return true;
}
?>

http://us.php.net/manual/en/function.imagecopyresampled.php#77679

phpThumb 速度を上げるために可能な限り ImageMagick を使用し (必要に応じて GD にフォールバックします)、サーバーの負荷を軽減するためにかなりうまくキャッシュしているようです。試してみると非常に軽量です (画像のサイズを変更するには、グラフィック ファイル名と出力サイズを含む GET クエリで phpThumb.php を呼び出すだけです)。そのため、ニーズを満たすかどうかを試してみるとよいでしょう。

大きな画像の場合は、ImageMagick での画像ロード時に libjpeg を使用してサイズを変更します。これにより、メモリ使用量が大幅に削減され、パフォーマンスが向上します。これは GD では不可能です。

$im = new Imagick();
try {
  $im->pingImage($file_name);
} catch (ImagickException $e) {
  throw new Exception(_('Invalid or corrupted image file, please try uploading another image.'));
}

$width  = $im->getImageWidth();
$height = $im->getImageHeight();
if ($width > $config['width_threshold'] || $height > $config['height_threshold'])
{
  try {
/* send thumbnail parameters to Imagick so that libjpeg can resize images
 * as they are loaded instead of consuming additional resources to pass back
 * to PHP.
 */
    $fitbyWidth = ($config['width_threshold'] / $width) > ($config['height_threshold'] / $height);
    $aspectRatio = $height / $width;
    if ($fitbyWidth) {
      $im->setSize($config['width_threshold'], abs($width * $aspectRatio));
    } else {
      $im->setSize(abs($height / $aspectRatio), $config['height_threshold']);
    }
    $im->readImage($file_name);

/* Imagick::thumbnailImage(fit = true) has a bug that it does fit both dimensions
 */
//  $im->thumbnailImage($config['width_threshold'], $config['height_threshold'], true);

// workaround:
    if ($fitbyWidth) {
      $im->thumbnailImage($config['width_threshold'], 0, false);
    } else {
      $im->thumbnailImage(0, $config['height_threshold'], false);
    }

    $im->setImageFileName($thumbnail_name);
    $im->writeImage();
  }
  catch (ImagickException $e)
  {
    header('HTTP/1.1 500 Internal Server Error');
    throw new Exception(_('An error occured reszing the image.'));
  }
}

/* cleanup Imagick
 */
$im->destroy();

あなたの質問から、あなたはGDにちょっと新しいようです、私は私の経験をいくつか共有します、多分これは少し話題から外れていますが、私はそれがあなたのようなGDに新しい人に役立つと思います:

ステップ 1、ファイルを検証します。 次の関数を使用して、 $_FILES['image']['tmp_name'] ファイルは有効なファイルです:

   function getContentsFromImage($image) {
      if (@is_file($image) == true) {
         return file_get_contents($image);
      } else {
         throw new \Exception('Invalid image');
      }
   }
   $contents = getContentsFromImage($_FILES['image']['tmp_name']);

ステップ 2、ファイル形式を取得する ファイル(中身)のファイル形式を確認するには、finfo拡張子を付けて次の関数を試してください。なぜ使わないのかと言うでしょう。 $_FILES["image"]["type"] ファイル形式を確認するには?なぜなら、それは のみ 誰かが最初に呼び出したファイルの名前を変更した場合は、ファイルの内容ではなくファイル拡張子を確認してください。 世界.png世界.jpg, $_FILES["image"]["type"] pngではなくjpegを返すので、 $_FILES["image"]["type"] 間違った結果が返される可能性があります。

   function getFormatFromContents($contents) {
      $finfo = new \finfo();
      $mimetype = $finfo->buffer($contents, FILEINFO_MIME_TYPE);
      switch ($mimetype) {
         case 'image/jpeg':
            return 'jpeg';
            break;
         case 'image/png':
            return 'png';
            break;
         case 'image/gif':
            return 'gif';
            break;
         default:
            throw new \Exception('Unknown or unsupported image format');
      }
   }
   $format = getFormatFromContents($contents);

Step.3、GDリソースの取得 以前のコンテンツから GD リソースを取得します。

   function getGDResourceFromContents($contents) {
      $resource = @imagecreatefromstring($contents);
      if ($resource == false) {
         throw new \Exception('Cannot process image');
      }
      return $resource;
   }
   $resource = getGDResourceFromContents($contents);

ステップ 4、画像の寸法を取得する 次の簡単なコードで画像の寸法を取得できるようになりました。

  $width = imagesx($resource);
  $height = imagesy($resource);

今、 元の画像からどのような変数を取得したかを見てみましょう。

       $contents, $format, $resource, $width, $height
       OK, lets move on

ステップ 5、サイズ変更された画像引数を計算する このステップはあなたの質問に関連しています。次の関数の目的は、GD 関数のサイズ変更引数を取得することです。 imagecopyresampled(), コードは少し長いですが、うまく機能し、3 つのオプションもあります。伸ばしたり、縮めたり、埋めたりします。

ストレッチ:出力画像の寸法は、設定した新しい寸法と同じになります。高さと幅の比率が維持されません。

縮む:出力画像の寸法は指定した新しい寸法を超えず、画像の高さと幅の比率が維持されます。

埋める:出力画像の寸法は、指定した新しい寸法と同じになります。 トリミングとサイズ変更 必要に応じて画像を追加し、画像の高さと幅の比率を維持します。 このオプションは質問に必要なものです。

   function getResizeArgs($width, $height, $newwidth, $newheight, $option) {
      if ($option === 'stretch') {
         if ($width === $newwidth && $height === $newheight) {
            return false;
         }
         $dst_w = $newwidth;
         $dst_h = $newheight;
         $src_w = $width;
         $src_h = $height;
         $src_x = 0;
         $src_y = 0;
      } else if ($option === 'shrink') {
         if ($width <= $newwidth && $height <= $newheight) {
            return false;
         } else if ($width / $height >= $newwidth / $newheight) {
            $dst_w = $newwidth;
            $dst_h = (int) round(($newwidth * $height) / $width);
         } else {
            $dst_w = (int) round(($newheight * $width) / $height);
            $dst_h = $newheight;
         }
         $src_x = 0;
         $src_y = 0;
         $src_w = $width;
         $src_h = $height;
      } else if ($option === 'fill') {
         if ($width === $newwidth && $height === $newheight) {
            return false;
         }
         if ($width / $height >= $newwidth / $newheight) {
            $src_w = (int) round(($newwidth * $height) / $newheight);
            $src_h = $height;
            $src_x = (int) round(($width - $src_w) / 2);
            $src_y = 0;
         } else {
            $src_w = $width;
            $src_h = (int) round(($width * $newheight) / $newwidth);
            $src_x = 0;
            $src_y = (int) round(($height - $src_h) / 2);
         }
         $dst_w = $newwidth;
         $dst_h = $newheight;
      }
      if ($src_w < 1 || $src_h < 1) {
         throw new \Exception('Image width or height is too small');
      }
      return array(
          'dst_x' => 0,
          'dst_y' => 0,
          'src_x' => $src_x,
          'src_y' => $src_y,
          'dst_w' => $dst_w,
          'dst_h' => $dst_h,
          'src_w' => $src_w,
          'src_h' => $src_h
      );
   }
   $args = getResizeArgs($width, $height, 150, 170, 'fill');

ステップ6、画像のサイズを変更する 使用 $args, $width, $height, $format 上記で取得した $resource を次の関数に入力し、サイズ変更された画像の新しいリソースを取得します。

   function runResize($width, $height, $format, $resource, $args) {
      if ($args === false) {
         return; //if $args equal to false, this means no resize occurs;
      }
      $newimage = imagecreatetruecolor($args['dst_w'], $args['dst_h']);
      if ($format === 'png') {
         imagealphablending($newimage, false);
         imagesavealpha($newimage, true);
         $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);
         imagefill($newimage, 0, 0, $transparentindex);
      } else if ($format === 'gif') {
         $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);
         imagefill($newimage, 0, 0, $transparentindex);
         imagecolortransparent($newimage, $transparentindex);
      }
      imagecopyresampled($newimage, $resource, $args['dst_x'], $args['dst_y'], $args['src_x'], $args['src_y'], $args['dst_w'], $args['dst_h'], $args['src_w'], $args['src_h']);
      imagedestroy($resource);
      return $newimage;
   }
   $newresource = runResize($width, $height, $format, $resource, $args);

ステップ 7、新しいコンテンツを取得する, 次の関数を使用して、新しい GD リソースからコンテンツを取得します。

   function getContentsFromGDResource($resource, $format) {
      ob_start();
      switch ($format) {
         case 'gif':
            imagegif($resource);
            break;
         case 'jpeg':
            imagejpeg($resource, NULL, 100);
            break;
         case 'png':
            imagepng($resource, NULL, 9);
      }
      $contents = ob_get_contents();
      ob_end_clean();
      return $contents;
   }
   $newcontents = getContentsFromGDResource($newresource, $format);

ステップ 8 拡張機能を取得する, 次の関数を使用して、画像形式から拡張子を取得します(画像形式は画像拡張子と同じではないことに注意してください)。

   function getExtensionFromFormat($format) {
      switch ($format) {
         case 'gif':
            return 'gif';
            break;
         case 'jpeg':
            return 'jpg';
            break;
         case 'png':
            return 'png';
      }
   }
   $extension = getExtensionFromFormat($format);

ステップ9 画像を保存する mike という名前のユーザーがいる場合、次の操作を実行すると、この PHP スクリプトと同じフォルダーに保存されます。

$user_name = 'mike';
$filename = $user_name . '.' . $extension;
file_put_contents($filename, $newcontents);

ステップ 10 リソースを破棄する GD リソースを破棄することを忘れないでください。

imagedestroy($newresource);

または、すべてのコードをクラスに記述し、単純に以下を使用することもできます。

   public function __destruct() {
      @imagedestroy($this->resource);
   }

チップ

多くの問題が発生する可能性があるため、ユーザーがアップロードしたファイル形式を変換しないことをお勧めします。

次の方針に沿って作業することをお勧めします。

  1. アップロードされたファイルに対して getimagesize( ) を実行して、画像のタイプとサイズを確認します。
  2. アップロードされた 700x700px 未満の JPEG 画像を宛先フォルダーに「そのまま」保存します。
  3. 中サイズの画像には GD ライブラリを使用します (コード サンプルについては、この記事を参照してください: PHP と GD ライブラリを使用して画像のサイズを変更する)
  4. 大きな画像には ImageMagick を使用してください。必要に応じて、バックグラウンドで ImageMagick を使用できます。

ImageMagick をバックグラウンドで使用するには、アップロードされたファイルを一時フォルダーに移動し、すべてのファイルを jpeg に「変換」し、それに応じてサイズを変更する CRON ジョブをスケジュールします。次のコマンド構文を参照してください。 imagemagick-コマンドライン処理

ファイルがアップロードされ、処理がスケジュールされていることをユーザーに通知できます。CRON ジョブは、特定の間隔で毎日実行されるようにスケジュールできます。画像が 2 回処理されないように、処理後にソース画像を削除することもできます。

Imagick ライブラリについては素晴らしいことを聞いていましたが、残念ながら職場のコンピュータにも自宅にもインストールできませんでした (信じてください、私はあらゆる種類のフォーラムに何時間も費やしました)。

その後、この PHP クラスを試してみることにしました。

http://www.verot.net/php_class_upload.htm

これはとてもクールで、あらゆる種類の画像のサイズを変更できます (JPG に変換することもできます)。

ImageMagick はマルチスレッドであるため、高速に見えますが、実際には GD よりも多くのリソースを使用します。すべて GD を使用して複数の PHP スクリプトを並行して実行した場合、単純な操作の速度では ImageMagick を上回るでしょう。ExactImage は ImageMagick よりも強力ではありませんが、はるかに高速です。ただし、PHP からは利用できません。サーバーにインストールして実行する必要があります。 exec.

大きな画像の場合は、 phpThumb(). 。使用方法は次のとおりです。 http://abcoder.com/php/problem-with-resizing-corrupted-images-using-php-image-functions/. 。大きな破損した画像にも機能します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top