Nona Blog

Laravel Image Intervention — Remove Black Background

I am currently working a on a Laravel project that is using image intervention to handle image resizing.

I was battling with this damn issue of my images resizing and having a black background, as attached as below:

Image for post

Luckily I ran into this StackOverflow post which explained how to to remove it. Here’s the solution in a nutshell:

  1. Create the image,
  2. Resize it maintaining aspect ratio
  3. Add image on top of a canvas that has a white background where the image is centered.

Here is my implementation of the fix in actual code:

// Create Image
$image = Image::make('path/to/image');

// Resize image to desired dimensions where:
// 1. The largest side fits within the limit; 
// 2. The smaller side will be scaled to maintain the original 
//    aspect ratio;
$image
  ->resize(
      $dimension['width'], 
      $dimension['height'], 
      function ($constraint) {
         $constraint->aspectRatio();
         $constraint->upsize();
      }
    );

// Add a background canvas to the image
$image
  ->resizeCanvas(
      $dimension['width'],  // use the same width
      $dimension['height'], // use the same height
      'center',             // centre the image on the canvas
      false,                // don't apply relative mode 
      '#ffffff'             // add a white background to the image
    );

I hope this helps someone else out there in the ether 🙂

Nona helps funded businesses accelerate their software projects. If you’d like to soundboard your tech project or your development team, book a consultation with us and we can chat through it! 

Dom Bauer

Dom Bauer

Junior Developer - Nona

Add comment