如何使用 Laravel 中的干预图像操作库以自定义比例调整图像大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23109206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How resize image with custom ratio using Intervention image manipulation library in laravel
提问by BlackHyman
I want to resize an image with custom ratio (width:height)=(5:1)
我想用自定义比例调整图像大小 (width:height)=(5:1)
Using Intervention image manipulation libraryin
laravel
.It's not a problem if the image stretches. I don't want to put any fixed height or width.
使用干预的图像处理库在
laravel
。如果图像拉伸,这不是问题。我不想放置任何固定的高度或宽度。
so please give me some suggestions.
所以请给我一些建议。
采纳答案by interstellarDust
I don't think intervention image library has this option in their resize function. you can use getimagesize()
php function to get the height and width and divide width with 5 (in your case its 5 because you want 5:1) to get the height.
我认为干预图像库在其调整大小功能中没有此选项。您可以使用getimagesize()
php函数获取高度和宽度并将宽度除以5(在您的情况下为5,因为您想要5:1)以获得高度。
$image=getimagesize($image_file);
$width=$image[0]; // $image[0] is the width
$height=$image[0]/5; // $image[1] is the height
Than you can just use your intervention's resize()
function to resize to that height and width.
比您可以使用干预的resize()
功能调整到该高度和宽度。
Image::make($source_image)
->resize($width,$height ,false,false)
->save($destination);`
回答by Meinama
I think the best solution might be, to use fit()from the library.
我认为最好的解决方案可能是使用库中的fit()。
Like this:
像这样:
// open 4/3 image for example
$image = Image::make('foo.jpg');
// your desired ratio
$ratio = 16/9;
// resize
$image->fit($image->width(), intval($image->width() / $ratio));
It don't stretches the image.
它不会拉伸图像。
回答by Patrick Wang
I choose fit() rather than resize() to modify the picture avoiding to stretch the image to much.
我选择 fit() 而不是 resize() 来修改图片,避免将图像拉伸太多。
I use a php snippet in my project, which might be helpful.
我在我的项目中使用了一个 php 片段,这可能会有所帮助。
$img = Image::make($pictureOriginalPath);
// Picture ratio
$ratio = 4/3;
// Check the current size of img is appropriate or not,
// if ratio of current img is greater than 1.33, then crop
if(intval($img->width()/$ratio > $img->height()))
{
// Fit the img to ratio of 4:3, based on the height
$img->fit(intval($img->height() * $ratio),$img->height());
}
else
{
// Fit the img to ratio of 4:3, based on the width
$img->fit($img->width(), intval($img->width()/$ratio));
}
// Save, still need throw exception
$img->save($pictureNewPath);