Search code examples
laravelimagegdintervention

How can I put a rectangular photo in a square photo?


I have a rectangular photo. I want to put it in a square photo. So that the whole rectangle is placed in the square. (I want to have the entire rectangle image in the square photo!)

I tried this:

$width = 500;
$height = 500;
$img = Image::make($path);
$img->width() > $img->height() ? $width=null : $height=null;
$img->resize($width, $height, function ($constraint) {
    $constraint->aspectRatio();
})->fit(500, 500, function ($constraint) {
    $constraint->upsize();
});

But it cut some portion of main image. How can I correct that?


Solution

  • You can make your image to its original aspect ratio but fit it in the size of the square without crop it. As i see you use Intervention Image so you can try:

    $img = Image::make($path)->resize($width, $height, function ($constraint) {
        $constraint->aspectRatio();
    });
    

    With that, you tell Intervention to create an image and choose to fit the square as per width if your image's width is bigger than height or per height if your image's height is bigger than width.

    If you also want a square around you can use:

    $square = Image::canvas($width, $height, '#101010')->insert($img, 'center');