Laravel has Intervention Image
, with which you can resize images
// create instance
$img = Image::make('public/foo.jpg');
// resize image to fixed size
$img->resize(300, 200);
Everything is fine if the uploaded image has a size of 3000 x 2000 and we will make 300 x 200 from it.
But if we load images with different heights and widths, and do a 300 x 200 resize, then the images will stretch and look awful.
I need them to be cut a little at the edges.
I have tried using $img->fit(300, 200);
but it cuts too much.
Is it possible to do two steps in Intervention Image
for resizing, for example, defining the size and removing a few unnecessary parts to make the picture look more or less normal?
CodePudding user response:
To remove a few unnecessary parts you can use the crop() function first and then resize the image maintaining its aspect ration.
$img->crop(width, height, x, y);
This function cuts out a rectangular part of the current image with given width and height. Define optional x,y coordinates to move the top-left corner of the cutout to a certain position. By default the rectangular part will be centered on the current image if you do not provide the x,y co-ordinates.
After cropping the image, you can resize the image maintaining its aspect ration, so the image will not look stretchy or abnormal.
// resize the image to a width of 300 and constrain aspect ratio (auto height)
$img->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});
// resize the image to a height of 200 and constrain aspect ratio (auto width)
$img->resize(null, 200, function ($constraint) {
$constraint->aspectRatio();
});
However, if you always want the image to be a specific dimension, which is in your case 300 X 200 , You can try the fit function with the callback functionality to retain maximal original image size.
// add callback functionality to retain maximal original image size
$img->fit(300, 200, function ($constraint) {
$constraint->upsize();
});