title: Crop from the center and resize in PHP (function)
body: <p>I want to have a function that resizes to a specific height en weight of an image without losing the aspect ratio. So first i want to crop it and then resizing it.</p>
  
  <p>This is what i got so far:</p>
  
  <pre><code>function image_resize($src, $dst, $width, $height, $crop=1){
  
    if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";
  
    $type = strtolower(substr(strrchr($src,"."),1));
    if($type == 'jpeg') $type = 'jpg';
    switch($type){
      case 'bmp': $img = imagecreatefromwbmp($src); break;
      case 'gif': $img = imagecreatefromgif($src); break;
      case 'jpg': $img = imagecreatefromjpeg($src); break;
      case 'png': $img = imagecreatefrompng($src); break;
      default : return "Unsupported picture type!";
    }
  
    // resize
      $originalW = $w;
      $originalH = $h;
  
    if($crop){
      if($w &lt; $width or $h &lt; $height) return "Picture is too small!";
      $ratio = max($width/$w, $height/$h);
      $h = $height / $ratio;
      $x = ($w - $width / $ratio) / 2;
      $w = $width / $ratio;
    }
    else{
      if($w &lt; $width and $h &lt; $height) return "Picture is too small!";
      $ratio = min($width/$w, $height/$h);
      $width = $w * $ratio;
      $height = $h * $ratio;
      $x = 0;
    }
  
    $new = imagecreatetruecolor($width, $height);
  
    // preserve transparency
    if($type == "gif" or $type == "png"){
      imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
      imagealphablending($new, false);
      imagesavealpha($new, true);
    }
  
    imagecopyresampled($new, $img, 0, 0, ($originalW - $width)/2, ($originalH - $height)/2, $width, $height, $w, $h);
  
  
    switch($type){
      case 'bmp': imagewbmp($new, $dst); break;
      case 'gif': imagegif($new, $dst); break;
      case 'jpg': imagejpeg($new, $dst); break;
      case 'png': imagepng($new, $dst); break;
    }
    return true;
  }       
  </code></pre>
  
  <p>The function is working fine. But i still have a problem. For example: When i resize a portrait image thats (300 × 450) to (260 x 140) i get a black side bar which i dont want. </p>
  
  <p>Here are the 2 images: </p>
  
  <p><img src="https://i.stack.imgur.com/smQGZ.jpg" alt="postimage.org/image/6vvq5l5sn"> 
  <img src="https://i.stack.imgur.com/QZFvm.jpg" alt="enter image description here"></p>