PHPで画像の縮小(サムネイル表示とかに)
phpでサムネイル表示向けに画像を縮小してみます。
細かくはツッコミどころもあるとは思いますが、いろいろと参考に作ってみるとざっとこんな感じです。
jpg, gif, pngを対象にしています。っていうかこれ以外の画像は縮小出力可能なんでしょうか?
<?php $fileName = "photo.jpg"; //縮小サイズ。基本4:3の比率で縮小する $w = 200; //width $h = 150; //height if (!file_exists($fileName)) { die('file not exist'); } if (isImage($fileName) == false) { die('not image'); return; } //画像情報の取得 $info = getimagesize($fileName); if ($info == FALSE) { die('not image'); return; } list($width, $height, $mime) = $info; $image = NULL; if ($mime == IMG_PNG) { $image = imagecreatefrompng($fileName); } else if ($mime == IMG_JPG) { $image = imagecreatefromjpeg($fileName); } else if ($mime == IMG_GIF) { $image = imagecreatefromgif($fileName); } else { die('not image'); return; } if ($image == NULL) { die('not image'); return; } if ($width == 0 || $height == 0) { //画像のサイズが取得できなかった場合画像リソースから再取得する $width = $imagesx($image); $height= $imagesy($image); } //必要となる幅の縮小サイズ $ws = $width - $w; //必要となる高さの縮小サイズ $hs = $height - $h; if ( $w >= $width && $h >= $height) { //縮小不要 $w = $width; $h = $height; } else if ( $hs > $ws) { //縦長 $w = $h / $height * $width; } else if ( $ws >= $hs) { //横長 $h = $w / $width * $height; } // 再サンプル $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $image, 0, 0, 0, 0, $w, $h, $width, $height); imagedestroy($image); // 出力 header('Content-type: image/png'); imagepng($dst); imagedestroy($dst); //------------------ /** * 連想配列から指定したキーの値を返します **/ function agv($array, $key, $default = NULL) { return isset($array[$key]) ? $array[$key]: $default; } /** * 拡張子を返します **/ function getFileExtention($fileName) { $parts = pathinfo($fileName); return agv($parts, 'extension'); } /** * 画像ファイルかどうか判定します **/ function isImage($fileName) { $exts = array('jpg','jpeg','gif','png'); $ext = strtolower(getFileExtention($fileName)); if (in_array($ext, $exts)) { return true; } else { return false; } } ?>