Resizing with a max width/height while keeping the original ratio using Intervention Image in Laravel

I know I am somewhat late to the race, but I have the answer you are looking for:

$width = 600; // your max width
$height = 600; // your max height
$img = IMG::make($uploaded_file);
$img->height() > $img->width() ? $width=null : $height=null;
$img->resize($width, $height, function ($constraint) {
    $constraint->aspectRatio();
});

An image of 1000x1000 would become 600x600.

An image of 2000x1000 would become 600x300. This would mean that the highest of the two values becomes 600, while the other gets constrained proportionally.

This is what this code does. Hope I can help someone.


As according to the Image Intervention Docs, you can do this in 3 simple ways

// resize the image to a width of 300 and constraint aspect ratio (auto height)
$img->resize(300, null, function ($constraint) {
    $constraint->aspectRatio();
});

// resize the image to a height of 200 and constraint aspect ratio (auto width)
$img->resize(null, 200, function ($constraint) {
    $constraint->aspectRatio();
});

// prevent possible upsizing
$img->resize(null, 400, function ($constraint) {
    $constraint->aspectRatio();
    $constraint->upsize();
});

Hope this helps...