I was checking out this laravel library to compress user uploaded images.http://image.intervention.io/
I was wondering if this is a good idea for user uploaded images (for profilepictures)? What if the user uploads a picture with a size of 1400x600 and it will be resized to 200x200? Will it be a stretched out image?
Yes, it will be stretched. You want to try fit()
method:
Combine cropping and resizing to format image in a smart way. The method will find the best fitting aspect ratio of your given width and height on the current image automatically, cut it out and resize it to the given dimension.
// crop the best fitting 1:1 ratio (200x200) and resize to 200x200 pixel
$img->fit(200);
Intervention is great for handling just this. Here's a quick code snippet to get you going in the right direction:
$resize_to = $this->sizes(); //some arbitrary array
//generate our custom image sizes
foreach ($resize_to as $idx => $width) {
if ($img = Image::make($file->getRealPath())) {
$img->resize(width, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->encode($encoding_options);
$img->save($path);
}
}
In the above we're looping over some array of widths that we want to have images resized to. Pay attention to the $constraints
that we've declared below. The aspectRatio()
ensures the image never loses it's aspect ratio. The ->upsize()
prevents images from being upsized and losing the resolution.
What you're asking for - resizing a 1400x600 image to 200x200
is unreasonable.
Instead, you should just resize to one dimension and make sure that your HTML can account for the rest. For example, in the above we only observe widths
. So we'll assume in your $this->sizes()
array, one of them is 200. But the image was a different ratio, so it didn't produce a 200x200, it produced a 200x150. Handle that in the HTML by using a flexbox super easily:
<div class="flex-box-centered">
<img class="flex-img" src="..."/>
</div>
And the CSS:
.flex-box-centered {
display:flex;
width:200px;
height:200px;
justify-content:center;
align-items:center;
background:#fff;
}
.flex-img {
display:flex;
width:100%;
height:auto;
}
And here's a jsfiddle illustrating this concept
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With