我想通过Laravel 4中的干预图像功能来调整图像大小,但为了保持图像的宽高比,这就是我的代码:
$image_make = Image::make($main_picture->getRealPath())->fit('245', '245', function($constraint) { $constraint->aspectRatio(); })->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name);
问题是,这并不能保持我的图像的宽高比,谢谢。
答案 0 :(得分:21)
如果您需要在限制范围内调整大小,则应使用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);
答案 1 :(得分:8)
只需将其调整为图像的最大宽度/高度,然后使画布适合最大宽度和宽度。所需高度
Image::make($main_picture->getRealPath())->resize(245, 245,
function ($constraint) {
$constraint->aspectRatio();
})
->resizeCanvas(245, 245)
->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name, 80);
答案 2 :(得分:3)
我知道这是一个旧线程,但是如果某天某人需要它,我会分享我的实现。
我的实现正在查看接收到的图像的长宽比,并将根据新的高度或宽度调整大小(如果需要)。
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
)。
以下是输出
100x100
。什么都不会发生,因为宽度
并且高度小于所需的480
大小。3000x1200
。这是一幅风景图像,并将其调整为:480x192
(保持宽高比)980x2300
。这是一幅肖像图像,并将其尺寸调整为:204x480
。1000x1000
。这是宽度和高度均相等的1:1宽高比图像。它将调整为:480x480
。答案 3 :(得分:0)
您需要在宽度或高度上使用null;
$ img-> resize(300,null,function($ constraint){$ constraint-> aspectRatio();});
或
$ img-> resize(null,200,函数($ constraint){$ constraint-> aspectRatio();});