Felix Maxime Felix Maxime - 1 month ago 23
PHP Question

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

I want to constrain an image only if they exceed either maximum dimensions while keeping the original ratio intact.

So let's say my parameters are a max height and width of 600.

An image of 1000x1000 would become 600x600, simple enough.

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.

Something like this

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


What would be the best way to go about this?

EDIT:

As per the comments, I tried this:

$medium = Image::make($file);

$medium->resize(null, 500, function ($constraint) {
$constraint->aspectRatio();
});

$medium->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
});
$medium->save( public_path('/uploads/artistUploads/medium-' . $filename , 90) );


This does not work. Only the first resize is applied, which in this case is width.

HOWEVER, turns out the original code does work. I simply assumed it wouldn't, but it does.

Answer

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...