我想通过Laravel 4中的干预图像功能来调整图像的大小,但为了保持图像的纵横比,我的代码如下所示:
$image_make = Image::make($main_picture->getRealPath())->fit('245', '245', function($constraint) { $constraint->aspectRatio(); })->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name);问题是,这不能保持我的图像的纵横比,谢谢。
发布于 2014-11-13 00:41:32
如果您需要在约束内调整大小,则应该使用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);发布于 2014-12-14 10:08:10
只需将其调整为图像的最大宽度/高度,并使画布适合所需的最大宽度和高度
Image::make($main_picture->getRealPath())->resize(245, 245,
function ($constraint) {
$constraint->aspectRatio();
})
->resizeCanvas(245, 245)
->save('images/articles/'.$gender.'/thumbnails/245x245/'.$picture_name, 80);发布于 2020-04-11 22:47:00
我知道这是一个古老的线程,但如果有一天有人需要我的实现,我将与您分享。
我的实现是查看接收到的图像的纵横比,并将根据新的高度或宽度调整大小(如果需要)。
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 (保留aspect ratio)480x192:980x2300。这是一个肖像图像,大小将调整为:204x480.1000x1000。这是宽高比为1:1的图像,宽度和高度相等。这将被调整为:480x480.https://stackoverflow.com/questions/26890539
复制相似问题