在 Yii2 中将图像从中心裁剪成最大的正方形想象一下?

Cropping an image from the center into the largest square you can make in Yii2 Imagine?

我使用的是 Yii2 扩展 Imagine,我需要根据用户上传的内容制作 150x150 图片。

目前我正在做这样的事情:

use yii\imagine\Image;

....

Image::thumbnail($save_path, $img_size, $img_size)->save($save_path);

显然,如果其中一个维度在调整后小于 150px,这可能会导致问题。

所以我主要想弄清楚的是如何将图像裁剪成 正方形 调整大小之前,所以当我调整它的大小时,不会有任何 宽高比 问题。

现在,我知道您可以使用以下内容裁剪图像:

Image::crop($save_path, $img_size, $img_size, [5, 5]);

但问题是这样做 之前 调整图像大小可能不会给你你想要的,因为图像可能太大并裁剪它 之后 调整大小也不起作用,因为一维可能已经减小到 < 150px.

所以我要解决的问题是如何在 之前裁剪图像 将大小调整为 最大 可能的正方形 从中心向外?

编辑:

好的,我已经想出办法来处理这个问题,但想知道是否有办法轻松完成以下操作,还是我需要自己编写代码?

不能只用Image::thumbnail()的第四个参数吗?

Image::thumbnail($save_path, $img_size, $img_size, Image\ImageInterface::THUMBNAIL_INSET)->save($save_path);

来自 http://www.yiiframework.com/doc-2.0/yii-imagine-baseimage.html#thumbnail()-detail

If thumbnail mode is ImageInterface::THUMBNAIL_INSET, the original image is scaled down so it is fully contained within the thumbnail dimensions. The rest is filled with background that could be configured via yii\imagine\Image::$thumbnailBackgroundColor and yii\imagine\Image::$thumbnailBackgroundAlpha.

再试一次:p

<?php

use yii\imagine\Image;
use Imagine\Image\Box;
use Imagine\Image\Point;

// ...

$thumbnail = Image::thumbnail($save_path, $img_size, $img_size);
$size = $thumbnail->getSize();
if ($size->getWidth() < $img_size or $size->getHeight() < $img_size) {
    $white = Image::getImagine()->create(new Box($img_size, $img_size));
    $thumbnail = $white->paste($thumbnail, new Point($img_size / 2 - $size->getWidth() / 2, $img_size / 2 - $size->getHeight() / 2));
}
$thumbnail->save($save_path);