エントリー

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 に変更すると、アンチエイリアスが有効になります。

ページ移動

コメント

  • コメントはまだありません。

コメント登録

  • コメントを入力してください。
登録フォーム
名前
メールアドレス
URL
コメント
閲覧制限
投稿キー(スパム対策に、投稿キー を半角で入力してください。)

ユーティリティ

2010年03月

- 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 - - -

検索

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

Feed

03月13日のブックマーク

RSSリーダー

  • JavaScriptをONにすると、RSSリーダーが表示されます。

利用ツール