The intervention image library is a really useful tool to manipulate images linearly without so much hassle. One of the things I had to achieve recently was to create the thumbnail version of any uploaded image in a Symfony project. As I said, working with Image Intervention is pretty comfortable, so I simply used the resize method providing the new width of 256px and a null height (because I though it would process the aspect ratio automatically):
<?php
use Intervention\Image\ImageManager;
$manager = new ImageManager();
$sourceImage = "images/source.jpg";
$destinationImage = "images/destination.jpg";
$image = $manager->make($source)->resize(256, null);
$image->save($destinationImage);
However, the aspect ratio wasn't conserved because the output image got distorted:
After reading the documentation I found out that the problem was that I only provided the width of the new image and didn't add the constraint to keep the aspect ratio. To solve this problem I used the following code instead:
<?php
use Intervention\Image\ImageManager;
$manager = new ImageManager();
$sourceImage = "images/source.jpg";
$destinationImage = "images/destination.jpg";
// Resize preserving the image aspect ratio
$image = $manager->make($source)->resize(256, null, function ($constraint) {
$constraint->aspectRatio();
// if you need to prevent upsizing, you can add:
// $constraint->upsize();
});
$image->save($destinationImage);
This time the thumbnail was created respecting the aspect ratio as I expected:
The same code applies when you want to adjust the height of the image instead of the width.
Happy coding ❤️!