imagecopyresampledでの画像リサイズ
PHPで画像リサイズを行うときimagemgick関数を使っていたが、GDライブラリでも簡単にリサイズできることが分かった。
PHP: imagecopysampled - Manual
※サンプル関数
function resizeImage($src, $dist, $tw, $th)
{
$percent = 1;
list($width, $height, $type, $attr) = getimagesize($src);
if ($type != 1 && $type != 2){
return false;
}
if ($width < = $tw && $height <= $th){
copy($src, $dist);
return true;
}
if ($width > $height){
if ($width > $tw){
$percent = $tw / $width;
}
}
else{
if ($height > $th){
$percent = $th / $height;
}
}
$newwidth = $width * $percent;
$newheight = $height * $percent;
if ($type == 1){
$source = imagecreatefromgif($src);
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagegif($thumb, $dist, 100);
}
else{
$source = imagecreatefromjpeg($src);
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb, $dist, 100);
}
return true;
}
GDライブラリの方がインストールも容易であり一般的なので、今後はGD関数を使うことにした。
ご意見、ご質問はこちらから
(ガイドミーメンバー登録が必要です)
(ガイドミーメンバー登録が必要です)