前回、リサイズ(縮小用)するときのサイズを求めるものを書きました。
pc.casey.jp » PHP|画像圧縮時のサイズを計算する :
https://pc.casey.jp/archives/2479
今回は、それを使って保存されているJPGファイルのリサイズを CakePHP 上で実際に行ってみました。
サンプル画像

▲truecolor ではないもの、Quality100(89kb)

▲truecolor のもの、Quality100(92kb)
スポンサードリンク

▲truecolor で Quality92のもの(35kb)
※元画像は巨大すぎるので結果のみ
処理例
function index(){
Configure::write('debug', 2);
// init
$max_x = 400;
$quality= 92;
// test data
$file = WWW_ROOT . "img_original.jpg";
$output= TMP . "output.jpg";
if($this->_makeThumbnail($file, $output, $max_x, $quality)){
debug('OK');
}else{
debug('NG');
}
}
/*
* by pc.casey.jp, GPL
*
* TEST RESULT
* -----------------------------------------------------
* Original Image File:
* w/X=5184, h/Y=3456, Size=5,910,079
*
* Output Image File (imagecreate)[Dirty]:
* w/X=400, h/Y=200, Size=90,281, Quality=100%
*
* Output Image File (imagecreatetruecolor):
* w/X=400, h/Y=266, Size=92,958, Quality=100%
* Output Image File (imagecreatetruecolor)[GoodJob]:
* w/X=400, h/Y=266, Size=35,051, Quality=92%
*
* Syukusen-kun Image File:
* w/X=400, h/Y=266, Size=34,723, Quality=92%
*/
function _makeThumbnail($file, $output, $max_x = 400, $quality = 92){
// open iamge and get X Y
if(!$img = @imagecreatefromjpeg($file)) return false;
list($img_x, $img_y) = getimagesize($file);
// $img_x= imagesx($img); // get x = width, 5184px
// $img_y= imagesy($img); // get y = height, 3456px
// new size
$new_y = $this->_getNewImageY($img_x, $img_y, $max_x);
// create image
//$new_img = imagecreate($max_x, $new_y);
$new_img = imagecreatetruecolor($max_x, $new_y);
// copy image
imagecopyresampled(
$new_img, //
$img, // original
0, // start x
0, // start y
0, // original start x
0, // original start y
$max_x, // w
$new_y, // h
$img_x, // original w
$img_y // original h
);
imagedestroy($img);
// output image
if(!@imagejpeg($new_img, $output, $quality)) return false;
return true;
}
参考文献
- 画像を拡大・縮小する方法 [PHP – 画像 – Tips] :
画像を拡大・縮小する方法 [PHP - 画像 - Tips] - 離れPHP島 :
離れPHP島


コメント