干预图像的长宽比

16

我希望通过Laravel 4中的 Intervention 图像功能调整图像大小,但要保持图像的长宽比,这是我的代码:

$image_make         = Image::make($main_picture->getRealPath())->fit('245', '245', function($constraint) { $constraint->aspectRatio(); })->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name);

问题在于这不保持我的图片的纵横比,谢谢。


@lukasgeiter 我的意思是resize()函数不会保持宽高比(抱歉),而fit()函数虽然能保持宽高比,但是会裁剪掉对我来说重要的图像部分... - sk4yb3n
那么如果比率不符合目标比率,你的预期结果究竟是什么? - lukasgeiter
@lukasgeiter,fit()函数确实按照我的期望调整了图像大小(245x245),但它也剪切了一些部分,我希望在不剪切任何部分的情况下调整大小... - sk4yb3n
在那些“没有图像”透明的区域中应该发生什么?黑色背景? - lukasgeiter
1
那剩下的245x245像素没有被图像覆盖的部分呢?应该是透明的(png)还是有颜色的? - lukasgeiter
显示剩余4条评论
4个回答

35
如果你需要在约束条件下调整大小,应该使用 resize 而不是 fit。如果你还需要将图像居中放置在约束条件中,应该创建一个新的 canvas 并将调整过大小的图像插入其中:
// This will generate an image with transparent background
// If you need to have a background you can pass a third parameter (e.g: '#000000')
$canvas = Image::canvas(245, 245);

$image  = Image::make($main_picture->getRealPath())->resize(245, 245, function($constraint)
{
    $constraint->aspectRatio();
});

$canvas->insert($image, 'center');
$canvas->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name);

漂亮的回答。这正是我需要的,可以让我的所有缩略图保持一致的大小。谢谢! - Merlevede
你如何为常规图像制作这个? 当用户上传多种类型的图像,如自然、动物、人类等时,由于没有固定的背景颜色,因此这些图像上存在多种背景颜色。 - Kabir Hossain
谢谢您的回答。我有一些问题:
  1. 根据您的代码,当您固定图像宽度时,图像将按比例调整大小,这将使图像高度发生变化。也许从图像的宽度中找到高度是未定义的。如何解决这个问题。
  2. 如果我使用Laravel Intervention包调整图像的宽度和高度,那么图像看起来就像原始图像的糟糕形状。我该如何解决这个问题。
- Kabir Hossain

12

将其调整为图像的最大宽度/高度,然后使画布适合所需的最大宽度和高度即可。

Image::make($main_picture->getRealPath())->resize(245, 245,
    function ($constraint) {
        $constraint->aspectRatio();
    })
->resizeCanvas(245, 245)
->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name, 80);

7

我知道这是一个旧线程,但如果有人以后需要,我想分享我的实现。

我的实现会查看接收到的图像的纵横比,并根据新的高度或宽度进行调整(如果需要调整)。

public function resizeImage($image, $requiredSize) {
    $width = $image->width();
    $height = $image->height();

    // Check if image resize is required or not
    if ($requiredSize >= $width && $requiredSize >= $height) return $image;

    $newWidth;
    $newHeight;

    $aspectRatio = $width/$height;
    if ($aspectRatio >= 1.0) {
        $newWidth = $requiredSize;
        $newHeight = $requiredSize / $aspectRatio;
    } else {
        $newWidth = $requiredSize * $aspectRatio;
        $newHeight = $requiredSize;
    }


    $image->resize($newWidth, $newHeight);
    return $image;
}

需要传递一个图片($image = Image::make($fileImage->getRealPath());)和所需的尺寸(例如: 480)。

以下是输出结果:

  1. 上传的图片: 100x100。不会发生任何变化,因为宽度和高度都小于所需的480尺寸。
  2. 上传的图片: 3000x1200。这是一张横向图片,将被缩放为:480x192(保持宽高比)。
  3. 上传的图片: 980x2300。这是一张纵向图片,将被缩放为:204x480
  4. 上传的图片: 1000x1000。这是一个1:1的宽高比图片,宽度和高度相等。将被缩放为:480x480

0

你需要在宽度或高度中使用null

$img->resize(300, null, function ($constraint) { $constraint->aspectRatio(); });

或者

$img->resize(null, 200, function ($constraint) { $constraint->aspectRatio(); });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接