How resize image with custom ratio using Intervention image manipulation library in laravel
Solution 1
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.
$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.
Image::make($source_image)
->resize($width,$height ,false,false)
->save($destination);`
Solution 2
I think the best solution might be, to use fit() from the library.
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.
Solution 3
I choose fit() rather than resize() to modify the picture avoiding to stretch the image to much.
I use a php snippet in my project, which might be helpful.
$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);
Tanvir
I am a web application developer.I like to learn and do new things and do exciting projects.I like to code whenever possible and develop my skill.
Updated on June 21, 2022Comments
-
Tanvir almost 2 years
I want to resize an image with custom ratio
(width:height)=(5:1)
Using Intervention image manipulation library in
laravel
.It's not a problem if the image stretches. I don't want to put any fixed height or width.
so please give me some suggestions.
-
Mokhlesur Rahman about 10 yearsthough this will stretch the image. :(
-
Tanvir about 10 yearsOh,How stupid I am.I didn't find this easy solution.Thanks bro...you saved my day....
-
Mokhlesur Rahman about 10 yearsI'm grateful that this solution worked for you... :)
-
Juni Brosas about 9 yearsor you can use the functions width() and height() in the intervention image object.