標籤:div dir str ring switch sam targe turn ima
/** * 置中裁剪圖片 * @param string $source [原圖路徑] * @param int $width [設定寬度] * @param int $height [設定高度] * @param string $target [目標路徑] * @return bool [裁剪結果] */function image_center_crop($source, $width, $height, $target){ if (!file_exists($source)) return false; /* 根據類型載入映像 */ switch (exif_imagetype($source)) { case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($source); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($source); break; case IMAGETYPE_GIF: $image = imagecreatefromgif($source); break; } if (!isset($image)) return false; /* 擷取映像尺寸資訊 */ $target_w = $width; $target_h = $height; $source_w = imagesx($image); $source_h = imagesy($image); /* 計算裁剪寬度和高度 */ $judge = (($source_w / $source_h) > ($target_w / $target_h)); $resize_w = $judge ? ($source_w * $target_h) / $source_h : $target_w; $resize_h = !$judge ? ($source_h * $target_w) / $source_w : $target_h; $start_x = $judge ? ($resize_w - $target_w) / 2 : 0; $start_y = !$judge ? ($resize_h - $target_h) / 2 : 0; /* 繪製置中縮放映像 */ $resize_img = imagecreatetruecolor($resize_w, $resize_h); imagecopyresampled($resize_img, $image, 0, 0, 0, 0, $resize_w, $resize_h, $source_w, $source_h); $target_img = imagecreatetruecolor($target_w, $target_h); imagecopy($target_img, $resize_img, 0, 0, $start_x, $start_y, $resize_w, $resize_h); /* 將圖片儲存至檔案 */ if (!file_exists(dirname($target))) mkdir(dirname($target), 0777, true); switch (exif_imagetype($source)) { case IMAGETYPE_JPEG: imagejpeg($target_img, $target); break; case IMAGETYPE_PNG: imagepng($target_img, $target); break; case IMAGETYPE_GIF: imagegif($target_img, $target); break; } return boolval(file_exists($target));}
PHP 映像置中裁剪函數