【サーバ】【画像処理】phpのgdで画像縮小して名前をつけて保存。

f:id:tsumayouzi:20121129222850p:plain

ひとつの画像をサムネイル・アイコン・バナー等をそれぞれ作る際、いちいちサイズを変え手書き出すのも面倒。

phpのgdという関数を使えばひとつの画像をアップロードした際に他のサイズも作って保存しておいてくれるようになた。

 

フォーム画面

echo '<form action="./gd.php" method="post" enctype="multipart/form-data">';
echo '<input type="file" name="image">';
echo '<input type="submit" value="送信する">';
echo '</form>';

 

画像生成画面

$dir = "./image/";	//アップロード用のディレクトリ
if (is_uploaded_file(@$_FILES["image"]["tmp_name"])) {
// ファイル名の文字コードを変換する
$file = $_FILES["image"]["name"];
$file1 = $dir.$_FILES["image"]["name"];
// テンポラリファイルを保存ディレクトリにコピー
copy($_FILES["image"]["tmp_name"],$file1);
//$rename = "image.gif";
//rename("$file1",$dir.$rename);
}
$file1 = $file1;                        // 元画像ファイル

//$file_name = $_POST['file_name'];
//$file = '"./image/'.$file_name.'"';
$file = explode("_m.gif", $file);
$file_after = $dir.$file[0].'_s.gif';

//対象となる画像を設定
$image = imagecreatefromgif($file1);

//取得した画像の一辺の長さ
$width  = imagesx( $image );
$height = imagesy( $image );
if ( $width >= $height ) {
    //横長の画像の時
    $side = $height;
    $x = floor( ( $width - $height ) / 2 );
    $y = 0;
    $width = $side;
} else {
    //縦長の画像の時
    $side = $width;
    $y = floor( ( $height - $width ) / 2 );
    $x = 0;
    $height = $side;
}

//$thumbnail_width と $thumbnail_height にはサムネイルの幅と高さを指定
//imagecreatetruecolor()でサムネイル画像の入れ物的なものを生成します。
$thumbnail_width  = 48;
$thumbnail_height = 48;
$thumbnail = imagecreatetruecolor( $thumbnail_width, $thumbnail_height );

//保存
imagecopyresampled( $thumbnail, $image, 0, 0, $x, $y, $thumbnail_width, $thumbnail_height, $width, $height );
imagegif( $thumbnail, $file_after );
if(imagecopyresampled){
	echo 'コピーできました。ファイル名は'.$file_after,'です。<a href="'.$file_after,'">ダウンロードはこちら</a>';
}