にゃじら的生活+あるふぁ 猫ふんじゃった

IT、プログラム開発、バンド、キーボードやサックス、ぐーたら猫の話など

PHP 画像のリサイズ (夏休みのプログラム その2)

PHP JPEGPNG画像をリサイズするプログラムのメモ
繰り返しがちょっとセンスがなくて気持ち悪い、、、

//引数 保存先・新しいファイル名・オリジナル画像ファイル・
    リサイズ幅・リサイズ縦・角度(必要な場合)
function imageResize($savePath, $newfileName, $image, 
                        $maxWidth, $maxHeight, $degrees=0){
    //画像のタイプを確認
    $imageType = @exif_imagetype($image);
    $source = false;

    switch( $imageType){
        case IMAGETYPE_JPEG: //元画像jpegの場合
        $source = imagecreatefromjpeg($image);
        break;

        case IMAGETYPE_PNG: //元画像pngの場合
        $source = imagecreatefrompng($image);
        break;

    }//switch

    if( !$source ){
        return false;
    }

    //画像の幅と高さを取得
    $width = ImageSx($source);
    $height = ImageSy($source);

    //新しいサイズを作成
    //とりあえず現在のサイズをいれておく
    $newWidth = $width;
    $newHeight = $height;

    if($width >= $maxWidth || $height >= $maxHeight ){
        if($width == $height) {
            //幅と高さが同じサイズだったら今回は幅にあわせる
            $newWidth = $maxWidth;
            $newHeight = $maxWidth;
        } else if($width > $height) {//横長の場合
            $newWidth = $maxWidth;
            $newHeight = $height*($maxWidth/$width);
        } else if($width < $height) {//縦長の場合
            $newWidth = $width*($maxHeight/$height);
            $newHeight = $maxHeight;
        }
    }

    //新しい画像のサイズを決める
    $resize = imagecreatetruecolor($newWidth , $newHeight);
    if( $imageType == IMAGETYPE_PNG){
        //透過処理 この処理をしておかないと背景が黒くなる
        imagealphablending($resize, false);
        imagesavealpha($resize, true);
    }

    //イメージの一部をコピー、伸縮
    imagecopyresampled($resize, $source,0,0,0,0, 
           $newWidth, $newHeight, $width, $height);

    //左周り
    $rotate = imagerotate($resize, $degrees, 0);
    $newImagePath = $savePath."/".$newfileName;

    switch( $imageType){

        case IMAGETYPE_JPEG;
        //JPEGで保存
        $newImagePath .= ".jpg";
        imagejpeg( $rotate, $newImagePath );
        break;

        case IMAGETYPE_PNG;
        //PNGで保存
        $newImagePath .= ".png";
        imagepng( $rotate, $newImagePath );
        break;

    }//switch

    //リソース破棄
    imagedestroy($source);
    imagedestroy($resize);

    return $newImagePath;
}