Intervention is great for handling just this. Here's a quick code snippet to get you going in the right direction:
$resize_to = $this->sizes(); //some arbitrary array
//generate our custom image sizes
foreach ($resize_to as $idx => $width) {
if ($img = Image::make($file->getRealPath())) {
$img->resize(width, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->encode($encoding_options);
$img->save($path);
}
}
In the above we're looping over some array of widths that we want to have images resized to. Pay attention to the $constraints
that we've declared below. The aspectRatio()
ensures the image never loses it's aspect ratio. The ->upsize()
prevents images from being upsized and losing the resolution.
What you're asking for - resizing a 1400x600 image to 200x200
is unreasonable.
Instead, you should just resize to one dimension and make sure that your HTML can account for the rest. For example, in the above we only observe widths
. So we'll assume in your $this->sizes()
array, one of them is 200. But the image was a different ratio, so it didn't produce a 200x200, it produced a 200x150. Handle that in the HTML by using a flexbox super easily:
<div class="flex-box-centered">
<img class="flex-img" src="..."/>
</div>
And the CSS:
.flex-box-centered {
display:flex;
width:200px;
height:200px;
justify-content:center;
align-items:center;
background:#fff;
}
.flex-img {
display:flex;
width:100%;
height:auto;
}
And here's a jsfiddle illustrating this concept