Search code examples
laravelimage-processingintervention

resize and Crop image with intervention/image


I want to resize crop image like below :

enter image description here

if image is lower than 500x400, scale up and crop, also if image is higher, scale down and crop.

i used some resize, canvas, fit and other functions but getting some confused at all.

I see users try to reach this post to find answer and i write here the comment:

thanks @snapey , it's my bad in coding, and ->fit() is doing that without any check, i used fit after some changes to image and so final result is get unexpected, but without any modify, fit works fine like expected.


@Snapey answer is correct, I'm using the same code, but my problem is that I modified the image before reaching this code and because of that, I'm getting unexpected results.


Solution

  • You have to test the dimensions to check if the photo is tall or wide, and then fit, crop ore resize as required.

    for example

            if($img->height() > $img->width()) {
                $img->resize(80,null, function ($constraint) {
                    $constraint->aspectRatio();
                });
            } else {
                $img->resize(null,80, function ($constraint) {
                    $constraint->aspectRatio();
                });
            }
    

    in this case, the resize specifies only one constraint and the other is set automatically using the aspect ratio constraint