首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >介入图像纵横比

介入图像纵横比
EN

Stack Overflow用户
提问于 2014-11-12 23:27:57
回答 4查看 16.4K关注 0票数 13

我想通过Laravel 4中的干预图像功能来调整图像的大小,但为了保持图像的纵横比,我的代码如下所示:

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

问题是,这不能保持我的图像的纵横比,谢谢。

EN

回答 4

Stack Overflow用户

发布于 2014-11-13 00:41:32

如果您需要在约束内调整大小,则应该使用resize而不是fit。如果您还需要使图像在约束中居中,则应创建一个新的canvas并在其中插入调整大小的图像:

代码语言:javascript
复制
// 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);
票数 30
EN

Stack Overflow用户

发布于 2014-12-14 10:08:10

只需将其调整为图像的最大宽度/高度,并使画布适合所需的最大宽度和高度

代码语言:javascript
复制
Image::make($main_picture->getRealPath())->resize(245, 245,
    function ($constraint) {
        $constraint->aspectRatio();
    })
->resizeCanvas(245, 245)
->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name, 80);
票数 10
EN

Stack Overflow用户

发布于 2020-04-11 22:47:00

我知道这是一个古老的线程,但如果有一天有人需要我的实现,我将与您分享。

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

代码语言:javascript
复制
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 (保留aspect ratio)
  3. Uploaded 480x192980x2300。这是一个肖像图像,大小将调整为:204x480.
  4. Uploaded image:1000x1000。这是宽高比为1:1的图像,宽度和高度相等。这将被调整为:480x480.
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26890539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档