PHP Intervention Image Resize image to fit shortest side to aspect ratio

image processingimage resizingPHP

How do I resize an image using Intervention Image maintaining the aspect ratio but making the image's shortest side fit the desired resize ratio.

E.g. a 800×400 image resized to fit 100×100 will be resized to 200×100

I tried this:

$image->resize($width, $height, function ($constraint) {
    $constraint->aspectRatio();
});

But it resizes the longest side to fit (e.g. 100×50).

Best Answer

Set width as null :

$height = 100;
$image = Image::make('800x400.jpg')->resize(null, $height, function ($constraint) {
    $constraint->aspectRatio();
});
$image->save('200X100.jpg', 60);

Programatically speaking, just find which side is larger and set it to null, i.e:

$width = 100;
$height = 100;
$image = Image::make('400x800.png');
$image->width() > $image->height() ? $width=null : $height=null;
$image->resize($width, $height, function ($constraint) {
    $constraint->aspectRatio();
});
$image->save('100x200.jpg', 60);