Search code examples
phpcodeignitercropaspect-ratio

Crop image to 16:9


I am using codiginter 3X version. How to crop all image to 16:9 and how to calculate correct width and height ?

I tried, but some images are not cropping to correct ratio 16:9 .

Example :

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();

Solution

  • Rather than width relative to height (ie. $width > $height) this technique compares aspect ratios to determine the shape of the incoming image and to calculate the new height or width.

    The answer also accounts for inputs that are already 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();
    }