Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 279
Felix Maxime Avatar asked Nov 07 '16 14:11

Felix Maxime


People also ask

How do I keep the same ratio as resizing?

Press-and-hold the Shift key, grab a corner point, and drag inward to resize the selection area. Because you're holding the Shift key as you scale, the aspect ratio (the same ratio as your original photo) remains exactly the same.

What is intervention image in laravel?

Intervention Image is a PHP image handling and manipulation library providing an easier and expressive way to create, edit, and compose images. The package includes ServiceProviders and Facades for easy Laravel integration.


1 Answers

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.

like image 139
Chris Palmer Breuer Avatar answered Oct 18 '22 21:10

Chris Palmer Breuer