k01ken’s b10g

He110 W0r1d!

PHPのImagickで縦横比を自動的に計算してサムネイル画像を作成する

開発環境はWindows10 Pro(64bit) + PHP 7.2.12。

横幅を指定するだけで自動的に高さも計算して、サムネイルを作ってくれるプログラムが見つからなかったので自分で書いた。

PHPでは、幅の数値を割るときに、floatに型変換しなくても、float型の値として小数点以下も表示してくれる。Pythonとは違うようだ。

ImagicKで画像を読み込むためには絶対パスで指定しないとエラーになる。
サムネイル画像はPHPのプログラムと同じディレクトリに入れている。

<?php

$Image = 'test.jpg';
$thumbImage = 'thumb_test.jpg';
$im = new Imagick(realpath($Image));

$width =  $im->getImageWidth();
$height = $im->getImageHeight();

// 仮に横幅を400と指定
$thumb_width = 400;

// 元の画像の横幅がリサイズしたい画像の横幅より大きければ
if($width > $thumb_width){
  $comparison = $width / $thumb_width;
  $thumb_height = $height / $comparison;
  $im->thumbnailImage($thumb_width, $thumb_height,true,true);
  $im->writeImage(__DIR__."\\".$saveImagePath);
}

?>


参考リンク
PHPでImageMagickを使ってサムネイル画像を作成する | Unskilled?
PHP: Imagick::thumbnailImage - Manual
PHP: realpath - Manual