Add space to image using Laravel 5 interference image to make a square image

Let's say I have a favorite square size, in which case it has width and height 2236 px

.

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

.

It doesn't matter what the size of the custom image is, but the point is that the image should be saved with the new size, but the user image should be in the center and middle of the square , and if the image is smaller than my favorite dimensions, it should be stretched, and if the image is larger, it must be compressed for my measurement .

Please take a look at this image: my plan

And here are some real-world examples: example 1 example 2

Does anyone have any experience with this situation and do you know how I can do this?

Thanks in Advance

+3


source to share


2 answers


Ok, thanks @Anton

for his hint, I did this to solve my problem:

An image is a 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
*/

      

+2


source


<?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');

      



+1


source







All Articles