JackD's avatar

Resize image with sample aspect ratio

Hi

I am using Image Intervention for the image adjustment before saving it, but i can't make it work to have them all same size but still with the same aspect ratio. How to achieve that? example is image will be save 500x500 but the image inside of it will be resize to fit inside the 500x500 without cropping and still with the same aspect ratio (portrait or landscape mode)

here is what i currently have for the image

$img->resize(500, 500)->save(Config::get('images.full_size') . $filename);
0 likes
9 replies
spekkionu's avatar

Try something like this.

$img->resize(500, 500, function ($constraint) {
    $constraint->aspectRatio();
});
JackD's avatar

@spekkionu thanks, the image has been resized but the width was not 500,

i tried it with this example image to upload 800x1600 but after saving the image it was resized to 223x500
though it remain the same aspect ratio but the width of the image canvas should be 500 too

thomaskim's avatar

So you want both width and height to be 500? Then, it's impossible to do this without cropping, in which case, fit() would be the method you are looking for.

spekkionu's avatar
Level 48

Ok, so you don't just want to resize the image you want to resize it and then pad it to be exactly 500x500.

What you need to do is create a 500x500 image with whatever background color you want to pad with then use the insert method to paste your resized image on top of it.

http://image.intervention.io/api/insert

// Resized image
$img->resize(500, 500, function ($constraint) {
    $constraint->aspectRatio();
});
// Canvas image
$canvas = Image::canvas(500, 500);
$canvas->insert($img, 'center');
$canvas->save();
5 likes
JackD's avatar

@thomaskim not actually cropping but to make fit the image inside a 500x500 with same aspect ratio and the excess not covered by image in the 500x500 will have default background color

JackD's avatar

@spekkionu thanks a lot i get now the idea, but i am getting a Class image does not exist within this part

$canvas = Image::canvas(500, 500);
spekkionu's avatar

You will need to import the facade into the current namespace by adding a use Image; to your file or you can access it using \Image::canvas()

You should have had to do the same thing to open the image you were resizing.

1 like
JackD's avatar

Thanks a lot, adding \ before image works well but the use Image produce error

Please or to participate in this conversation.