Search code examples
phpimage-processingimage-resizing

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


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 800x400 image resized to fit 100x100 will be resized to 200x100

I tried this:

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

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


Solution

  • 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 the larger side 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);