PHP图片缩放 加白边

/**
 * [cut_img 图片缩放加白边]
 * Author: 程威明
 * @param  array $imgs    图片路径数组
 * @param  array $info    图片宽高数组array('width','height')
 * @param  bool $cover    是否覆盖原图,默认不覆盖
 * @return array          若覆盖原图返回裁剪数量,不覆盖返回图片路径组成的数组
 */
function zoom_img($imgs=array(),$infoarr=array(500,500),$cover=false)
{
    //判断是否为数组(必须是一个以图片路径组成的数组)
    $imgs = is_array($imgs)?$imgs:array($imgs);

    $i=0;
    foreach($imgs as $file){
        //如果不覆盖原图,可重新定义图片保存路径
        if(false==$cover){
            $file = $file;
        }

        //要保存的宽
        $saveWidth = $infoarr[0];

        //要保存的高
        $saveHeight = $infoarr[1];

        //判断图片是否存在
        if(!file_exists($file)) continue;

        //获取图片信息
        $imgize = getimagesize($file);

        //图片宽度
        $width = $imgize[0];
        //图片高度
        $height = $imgize[1];

        //原宽高比
        $ratio = $width/$height;

        //判断图片原宽高比与裁剪宽高比的大小
        if($width>=$height){
            $height = $saveWidth/$ratio;
            $width = $saveWidth;
        }else{
            $width = $saveHeight*$ratio;
            $height = $saveHeight;
        }

        //创建源图的实例
        $src = imagecreatefromstring(file_get_contents($file));

        if(false!=$src){
            //创建图像
            $final_image = imagecreatetruecolor($saveWidth, $saveHeight);
            //定义颜色
            $color = imagecolorallocate($final_image, 255, 255, 255);
            //定义为透明色
            imagecolortransparent($final_image,$color);
            //填充
            imagefill($final_image, 0, 0, $color);
            $x = round(($saveWidth - $width) / 2);
            $y = round(($saveHeight - $height) / 2);
            imagecopyresized($final_image, $src, $x, $y, 0, 0, $width, $height,$imgize[0],$imgize[1]);
            //保存
            if(false==$cover){
                $file = rtrim(dirname($file),'/').'/z_'.basename($file);
                $save_file[] = $file;
            }
            imagejpeg($final_image,$file);
            imagedestroy($final_image);
            imagedestroy($src);
        }

        $i++;
    }

    if(false==$cover){
        return $save_file;
    }else{
        return $i;
    }
}

猜你喜欢

转载自blog.csdn.net/codercwm/article/details/53349554