Laravel Image Intervention — Remove Black Background

Dominic PrawnStar Bauer
2 min readAug 27, 2020

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 auto adding black background

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 canves
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 :)

Out of the darkness and into the light

--

--

Dominic PrawnStar Bauer

Slowly trying to piece the world together one idea at a time :).