Обрезать изображение до 16: 9

Я использую версию Codiginter 3X. Как обрезать все изображение до 16: 9 и как правильно рассчитать ширину и высоту?

Я пробовал, но некоторые изображения не обрезаются до правильного соотношения 16: 9.

Пример :

list($width, $height) = getimagesize($source_path);

if($width > $height) {

$height_set = ($width/16)*9;
$config_image = array(
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => FALSE,
'width' => $width,
'height' => $height_set,
);

} else {$height_set = ($width/16)*9;
$config_image = array(
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => FALSE,
'width' => $width,
'height' => $height_set,
);}

$this->image_lib->clear();
$this->image_lib->initialize($config_image);
$this->image_lib->crop();

1

Решение

Вместо ширины относительно высоты (т.е. $width > $height) эта методика сравнивает пропорции, чтобы определить форму входящего изображения и вычислить новую высоту или ширину.

Ответ также учитывает входные данные, которые уже 16: 9.

list($width, $height) = getimagesize($source_path);

//set this up now so it can be used if this image is already 16:9
$config_image = array(
'source_image' => $source_path,
'new_image' => "$target_path",
'maintain_ratio' => FALSE,
'height' => $height,
'width' => $width,
);
//Either $config_image['height'] or $config_image['width'] value
//will be replaced later if input is not already 16:9

$ratio_16by9 = 16 / 9; //a float with a value of ~1.77777777777778
$ratio_source = $width / $height;

//compare the source aspect ratio to 16:9 ratio
//float values to two decimal places is close enough for this comparison
$is_16x9 = round($ratio_source, 2) == round($ratio_16by9, 2);

if(!$is_16x9)
{
if($ratio_source < $ratio_16by9)
{
//taller than 16:9, cast answer to integer
$config_image['height'] = (int) round($width / $ratio_16by9);
}
else
{
//shorter than 16:9
$config_image['width'] = (int) round($height * $ratio_16by9);
}
}

//supply the config here and initialize() is done in __construct()
$this->load->library('image_lib', $config_image);

if(!$is_16x9)
{
$no_error = $this->image_lib->crop();
}
else
{
$no_error = $this->image_lib->resize(); //makes a copy of original
}

//report error if any
if($no_error === FALSE)
{
echo $this->image_lib->display_errors();
}
3

Другие решения

Других решений пока нет …