Home » Php » How resize image with custom ratio using Intervention image manipulation library in laravel

How resize image with custom ratio using Intervention image manipulation library in laravel

Posted by: admin November 30, 2017 Leave a comment

Questions:

I want to resize an image with custom ratio (width:height)=(5:1)

so please give me some suggestions.

Answers:

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);`

Questions:
Answers:

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.

Questions:
Answers:

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);