[PHP] JPEG/GIF/PNGファイルをリサイズ・トリミングしてローカルに保存する

JPEG/GIF/PNGファイルをリサイズ・トリミングしてローカルに保存する

JPEG/GIF/PNGファイルをリサイズ・トリミングしてローカルに保存する関数を作成した

横長でも縦長でも中央を中心に正方形にトリミングする。
出力ファイルはPNG形式だが
imagepng($out,$dir.”/”.$fileName.”.png”);
の部分をimagegif / imagejpegに変更すればよい

function resizeImage($url,$dir = ".",$fileName = "image"){
        list($w,$h,$type) = getimagesize($url);
        
        //出力する画像のサイズ
        $thumbW = 300;
        $thumbH = 300;
        //土台の画像を作る
        $thumbnail = imagecreatetruecolor($thumbW, $thumbH);
        
        if($w > $h){
            $diff  = ($w - $h) * 0.5; 
            $diffW = $h;
            $diffH = $h;
            $diffY = 0;
            $diffX = $diff;
        }elseif($w < $h){
            $diff  = ($h - $w) * 0.5; 
            $diffW = $w;
            $diffH = $w;
            $diffY = $diff;
            $diffX = 0;
        }elseif($w === $h){
            $diffW = $w;
            $diffH = $h;
            $diffY = 0;
            $diffX = 0;
        }
        
        
        switch($type){
            case IMAGETYPE_JPEG:
                $in = imagecreatefromjpeg($url);
                break;
            case IMAGETYPE_GIF:
                $in = imagecreatefromgif($url);
                break;
            case IMAGETYPE_PNG:
                $in = imagecreatefrompng($url);
                break;
        }
        
        $out = ImageCreateTrueColor($thumbW , $thumbH);
        imagealphablending($out, false);
        imagesavealpha($out, true);                    
        ImageCopyResampled($out,$in,0,0,$diffX,$diffY, $thumbW, $thumbH, $diffW, $diffH);
        
        imagepng($out,$dir."/".$fileName.".png");
        imagedestroy($out);
        imagedestroy($in);
}

処理前:600px x 426px
broccoli-1974801_640 (1)

処理後:300px x 300px
broccoli-1974801_640

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です