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:

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;
      function ($constraint) {

// Add a background canvas to the image
      $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 designs and builds intuitive software for FinTech businesses. If you’d like to accelerate your FinTech project, book a consultation with us!

Exit mobile version