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:
- Create the image,
- Resize it maintaining aspect ratio
- 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!
Add comment