【问题标题】:Add white space to image using Laravel 5 intervention image to make square image使用 Laravel 5 干预图像为图像添加空白以制作方形图像
【发布时间】:2018-04-08 21:09:08
【问题描述】:

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

我需要使用php intervention package 将我的图像以这种大小保存在我的服务器上。

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

请看这张图:

这些是一些真实的例子:

有没有人遇到过这种情况,你知道我该怎么做吗?

在此先感谢

【问题讨论】:

标签: php image laravel-5 intervention


【解决方案1】:
<?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');

【讨论】:

  • 感谢您的回复,但是这个脚本不会改变原图大小,只是将原图放在2236px的中心。 And如果图片宽度小于$width怎么办?
  • @Kiyarash 如果图片太小,尺寸会怎样?要拉伸吗?
  • 能否请您点击我在问题中的示例图片?
  • 这是您的脚本结果:dooor.ir/storage/nzvo6tZtbb2wTQvVq8XMoRfnP0IJGIbXqmNv4CDX/1.jpg。该链接将在我的开发过程中被禁用for future visitors
  • @Kiyarash 我看到您示例中的照片与此代码一样适合中心。你能解释一下不同之处吗?您评论中的 URL 图片非常小,您希望它拉伸到更大的宽度/高度吗?
【解决方案2】:

好吧,感谢@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
*/

【讨论】:

  • 横向和正方形的情况是一样的,你可以去掉正方形,用&gt;=代替&gt;进行横向检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-11
  • 2018-01-11
  • 2019-01-16
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多