php如何壓縮圖片?

位置:首頁 / 新聞中心 / 知識教程

知識教程 Admin 2024-06-19 10:51:42 565

應(yīng)用場景:

app 小程序 以及管理后臺上傳的圖片很大,占用空間且無用,則考慮進行圖片壓縮。

php代碼如下:

/**

     * 上傳后重新壓縮圖片

     * @param  $sourcePath 原圖

     * @param  $targetPath 保存路徑

     * @param  $quality    圖片質(zhì)量

     */

    function compressImage($sourcePath, $targetPath, $quality) {

        $info = getimagesize($sourcePath);

        $mime = $info['mime'];

        $width = $info[0];

        $height = $info[1];


        //壓縮后的圖片寬

        $newWidth = $width;

        //壓縮后的圖片高

        $newHeight = $height;

        

        // 壓縮到750寬

        if($width >= 750){

            $per = 750 / $width;//計算比例

            $newWidth = $width * $per;

            $newHeight = $height * $per;

        }


        $image_wp = imagecreatetruecolor($newWidth, $newHeight);


        switch($mime) {

            case 'image/jpeg':

                $image = imagecreatefromjpeg($sourcePath);

                break;

            case 'image/png':

                $image = imagecreatefrompng($sourcePath);

                break;

            case 'image/gif':

                $image = imagecreatefromgif($sourcePath);

                break;

            default:

                return false;

        }


        imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

        imagejpeg($image_wp, $targetPath, $quality);

        imagedestroy($image);

        imagedestroy($image_wp);


        return true;

    }


以上就是“php如何壓縮圖片?”的詳細內(nèi)容,更多請關(guān)注木子天禾科技其它相關(guān)文章!

15934152105 掃描微信