php如何压缩图片?

位置:首页 / 新闻中心 / 知识教程

知识教程 Admin 2024-06-19 10:51:42 1877

应用场景:

app 小程序 以及管理后台上传的图片很大,占用空间且无用,则考虑进行图片压缩。

php代码如下:

/**

     * 上传后重新压缩图片

     * @param  $sourcePath 原图

     * @param  $targetPath 保存路径

     * @param  $quality    图片质量

     */

    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如何压缩图片?”的详细内容,更多请关注木子天禾科技其它相关文章!

15934152105 扫描微信