将图像裁剪为16:9

时间:2017-09-25 15:39:54

标签: php codeigniter crop aspect-ratio

我正在使用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 个答案:

答案 0 :(得分:3)

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