Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add white space to image using Laravel 5 intervention image to make square image

Assume I have a favourite square size, and in this case it has 2236 px width and height.

I need to save my images in this size on my server using php intervention package.

It's not important that what is user's image size, but the point is that the image have to save with new size but the user image have to be center and middle of the square and if the picture is smaller than my favourite dimensions, it have to be stretch and if the image is bigger, it have to be compress to my dimension.

Please take a look at this picture: my plan

And these are some real examples: example 1 example 2

Does anyone any experience in this situation and do you know how can I do that?

Thanks in Advance

like image 210
Kiyarash Avatar asked Jun 04 '17 01:06

Kiyarash


2 Answers

<?php
$width = 2236;
$height = 2236;

$img = Image::make('image.jpg');

// we need to resize image, otherwise it will be cropped 
if ($img->width() > $width) { 
    $img->resize($width, null, function ($constraint) {
        $constraint->aspectRatio();
    });
}

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

$img->resizeCanvas($width, $height, 'center', false, '#ffffff');
$img->save('out.jpg');
like image 168
kopaty4 Avatar answered Oct 22 '22 03:10

kopaty4


Well, thanks to @Anton for his hint, I did this to solve my problem:

The image is horizontal rectangle, vertical rectangle or square.

I wrote these lines of code for every situation and it works great for my case

$img    = Image::make($image->getRealPath());

$width  = $img->width();
$height = $img->height();


/*
*  canvas
*/
$dimension = 2362;

$vertical   = (($width < $height) ? true : false);
$horizontal = (($width > $height) ? true : false);
$square     = (($width = $height) ? true : false);

if ($vertical) {
    $top = $bottom = 245;
    $newHeight = ($dimension) - ($bottom + $top);
    $img->resize(null, $newHeight, function ($constraint) {
        $constraint->aspectRatio();
    });

} else if ($horizontal) {
    $right = $left = 245;
    $newWidth = ($dimension) - ($right + $left);
    $img->resize($newWidth, null, function ($constraint) {
        $constraint->aspectRatio();
    });

} else if ($square) {
    $right = $left = 245;
    $newWidth = ($dimension) - ($left + $right);
    $img->resize($newWidth, null, function ($constraint) {
        $constraint->aspectRatio();
    });

}

$img->resizeCanvas($dimension, $dimension, 'center', false, '#ffffff');
$img->save(public_path("storage/{$token}/{$origFilename}"));
/*
* canvas
*/
like image 38
Kiyarash Avatar answered Oct 22 '22 05:10

Kiyarash