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

image manipulationlaravelPHP

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 1000×1000 would become 600×600, simple enough.

An image of 2000×1000 would become 600×300. 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.

Best Answer

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.

Related Topic