Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 924
BlackJack Avatar asked Apr 16 '14 12:04

BlackJack


3 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);
like image 35
Patrick Wang Avatar answered Nov 10 '22 08:11

Patrick Wang


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.

like image 136
Meinama Avatar answered Nov 10 '22 08:11

Meinama


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);`
like image 28
Mokhlesur Rahman Avatar answered Nov 10 '22 08:11

Mokhlesur Rahman