title: Imagemagick - Contain Image in Crop
body: <p>I don't use Imagemagick very often, which is why I don't know how to solve this problem. I also don't know how to phrase the question other than: How do I get the image to be cropped like the CSS property: background-size: contain; I haven't been able to find an answer, likely due to my phrasing.</p>
  
  <p>I need the image to be 200px, and "resized/cropped" so that it is not stretched, but contained by the width or height (dependent on the orientation of the image <code>width &gt; height = contain by width</code>)</p>
  
  <p>What I have so far:</p>
  
  <pre><code>$im = new Imagick($path);
  
  /* Resizing Operations */
  
  $gm = $im-&gt;getImageGeometry();
  $w = $gm['width'];
  $h = $gm['height'];
  
  if($h &lt; $w) {
      $nh = 200;
      $nw = (200 / $h) * $w;
  } else {
      $nw = 200;
      $nh = (200 / $w) * $h;
  }
  
  $im-&gt;resizeImage($nw, $nh, Imagick::FILTER_LANCZOS, true);
  $im-&gt;cropThumbnailImage(200,200);
  
  /* End Resizing Operations */
  </code></pre>
  
  <p><em>Which produces an image with the center chopped out.</em></p>
  
  <h2>Here's a visual example</h2>
  
  <p>We have this logo:</p>
  
  <p><img src="https://i.stack.imgur.com/BUb9X.jpg" alt="Original Logo"></p>
  
  <hr>
  
  <p>And then we want it to be constrained to 200px wide and 200px high, contained:</p>
  
  <h2><img src="https://i.stack.imgur.com/vtWoP.jpg" alt="resized"></h2>
  
  <p><strong>Essentially like setting the canvas height, while not adjusting the image height.</strong></p>