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:
And these are some real examples:
Does anyone any experience in this situation and do you know how can I do that?
Thanks in Advance
<?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');
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
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With