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; }}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章