使用 Laravel 5 干预图像为图像添加空白以制作方形图像

Kiy*_*ash 6 php image laravel-5 intervention

假设我有一个最喜欢的正方形尺寸,在这种情况下它有2236 px宽度和高度。

我需要使用php intervention package.

用户的图像尺寸是多少并不重要,但关键是图像必须以新尺寸保存,但用户图像必须位于正方形的中心和中间,如果图片小于我最喜欢的尺寸,则必须被拉伸,如果图像更大,它必须压缩到我的尺寸

请看一下这张照片: 我的计划

这些是一些真实的例子: 示例 1 例子2

有没有人在这种情况下有任何经验,你知道我该怎么做吗?

提前致谢

Ant*_*ton 5

<?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');
Run Code Online (Sandbox Code Playgroud)


Kiy*_*ash 5

好吧,感谢@Anton他的提示,我这样做是为了解决我的问题:

图像为水平矩形、垂直矩形或正方形。

我为每种情况编写了这些代码行,它对我的​​情况非常有用

$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
*/
Run Code Online (Sandbox Code Playgroud)