需求:將任意尺寸圖片 (如 1024x768) 裁切為固定正方形 (240x240),保持主體不變形、盡可能保留畫面核心內容。解法分兩步驟:等比縮放至可裁切尺寸 → 置中裁切。
x_axis 或 y_axis),執行置中裁切。<?php
$this->load->library('image_lib');
list($width, $height) = getimagesize("upload/123.jpg");
$config['image_library'] = 'gd2';
$config['source_image'] = 'upload/123.jpg';
$config['maintain_ratio'] = TRUE;
// 步驟 1:等比縮放
if ($width >= $height) {
$config['master_dim'] = 'height'; // 以高度為準
} else {
$config['master_dim'] = 'width'; // 以寬度為準
}
$config['width'] = 240;
$config['height'] = 240;
$this->image_lib->initialize($config);
$this->image_lib->resize();
// 步驟 2:置中裁切
$config['maintain_ratio'] = FALSE;
if ($width >= $height) {
// 橫向圖:計算縮放後寬度超出 240 的一半
$config['x_axis'] = floor(($width * 240 / $height - 240) / 2);
} else {
// 直向圖:計算縮放後高度超出 240 的一半
$config['y_axis'] = floor(($height * 240 / $width - 240) / 2);
}
$this->image_lib->initialize($config);
$this->image_lib->crop();
?>
master_dim:指定縮放基準維度 (width、height、auto)。maintain_ratio:TRUE 保持比例縮放;FALSE 強制依 width/height 裁切。x_axis/y_axis:裁切起始座標 (像素)。