Felix Maxime Felix Maxime - 9 months ago 81
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) {

What would be the best way to go about this?


As per the comments, I tried this:

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

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

$medium->resize(500, null, function ($constraint) {
$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 Source

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) {

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

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

Hope this helps...