PHPでの画像リサイズ
どうしてもWeb関係だとあまり使う機会が少ないので覚えてるうちにメモ。PHPのGDを使用した画像のリサイズ。
PHPのGDインストールは以下のコマンドで。インストール後にApache再起動。
yum -y install php-gd service httpd restart graceful
横幅を重視し、縦の方が長い場合は真ん中辺りを切り抜いて表示する。細かくはやってないので割り切れない時の処理とか適当です・・・・
<?php $image_url = "適当な画像url"; list($width, $height) = getimagesize($image_url); $image = imagecreatefromjpeg($image_url); //作成する画像サイズ $new_height = 100; $new_width = 200; //元画像の左上の位置 $y = 0; //圧縮比率を求める $rate = $new_width / $width; //縦の方が長い場合は画像の真ん中を表示 if ($width < $height) { $rate_height = $rate * $height; $rate_y = ($rate_height - $new_height) / 2; $y = $rate_y / $rate; } $image_p = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($image_p, $image, 0, 0, 0, $y, $width*$rate, $height*$rate, $width, $height); header('Content-Type: image/jpeg'); imagejpeg($image_p, null, 75); imagedestroy($image_p); exit;
そのうちWatchersにも適当に導入するかな・・・・やる気がでれば