エントリー

PHP+GDでサムネイル画像作成

自分用にメモ。

画像ファイルを元に、サムネイル画像を自動作成するプログラム。
以前メモしたつもりだったけど見当たらなかった…。

<?php

$dir  = 'test/';    //画像格納フォルダ
$file = 'test.png'; //画像ファイル名
$max  = 200;        //サムネイルのサイズ

if (preg_match('/\.gif$/i', $file)) {
  $image = imagecreatefromgif($dir . $file);
} elseif (preg_match('/\.(jpeg|jpg|jpe)$/i', $file)) {
  $image = imagecreatefromjpeg($dir . $file);
} elseif (preg_match('/\.png$/i', $file)) {
  $image = imagecreatefrompng($dir . $file);
}

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

if ($width > $height) {
  if ($width > $max) {
    $new_width  = $max;
    $new_height = ($new_width / $width) * $height;
  } else {
    $new_width  = $width;
    $new_height = $height;
  }
} else {
  if ($height > $max) {
    $new_height = $max;
    $new_width  = ($new_height / $height) * $width;
  } else {
    $new_width  = $width;
    $new_height = $height;
  }
}

$new_image = imagecreatetruecolor($new_width, $new_height);

imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); //アンチエイリアスなし
//imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); //アンチエイリアスあり

if (preg_match('/\.gif$/i', $file)) {
  imagegif($new_image, $dir . 'copy_of_' . $file);
} elseif (preg_match('/\.(jpeg|jpg|jpe)$/i', $file)) {
  imagejpeg($new_image, $dir . 'copy_of_' . $file, 70);
} elseif (preg_match('/\.png$/i', $file)) {
  imagepng($new_image, $dir . 'copy_of_' . $file);
}

imagedestroy($image);
imagedestroy($new_image);

?>

実行すると、ファイル名の先頭に copy_of_ を付加したファイル名でサムネイル画像が作成されます。
imagecopyresized の部分を imagecopyresampled に変更すると、アンチエイリアスが有効になります。

ページ移動

ユーティリティ

カテゴリー

検索

エントリー検索フォーム
キーワード

過去ログ

過去ログ表示フォーム
キーワード

Feed