Preloader
PHP
  • Estimated reading time: 1 Minute

How to resize an image preserving the aspect ratio using Image Intervention in PHP

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:

Resize Image Intervention Only Width

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:

Aspect Ratio Image Resizing

The same code applies when you want to adjust the height of the image instead of the width.

Happy coding ❤️!

Share:
Carlos Delgado

Carlos Delgado

Senior Software Engineer at Corvix. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Related articles
Weekly trending
The Test Is Whether the Thing You Built Actually Works
27 Jul, 2026
  • Estimated reading time: 2 Minutes
Does an SEO Agent Replace a Freelance SEO? A Hands-On Comparison
27 Jul, 2026
  • Estimated reading time: 5 Minutes
Why Paid Search Campaigns Fail at Lead Generation
27 Jul, 2026
  • Estimated reading time: 22 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.