将图片裁剪为 16:9

Crop image to 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();

而不是相对于高度的宽度(即 $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();
}