vincent15000's avatar

Programmatically remove white background from photos and convert them to png ?

Hello,

I need to upload some photo to a Laravel application.

Is there any way to remove programmtically the white background around the subject in the center of the image ?

Any way to do that with intervention/image ?

Or perhaps you know another tool or an API ?

Thanks for your help.

V

0 likes
6 replies
LaryAI's avatar
Level 58

To programmatically remove a white background from photos and convert them to PNG in a Laravel application, you have a few options. Unfortunately, Intervention/Image does not natively support background removal or advanced masking. However, you can use other tools or APIs for this purpose.

1. Using Remove.bg API

Remove.bg is a popular API for removing backgrounds from images. You can easily integrate it into your Laravel app.

Example using Guzzle HTTP client:

use Illuminate\Support\Facades\Http;

$response = Http::attach(
    'image_file', fopen($pathToUploadedImage, 'r')
)->post('https://api.remove.bg/v1.0/removebg', [
    'size' => 'auto',
    'format' => 'png',
], [
    'X-Api-Key' => 'YOUR_REMOVE_BG_API_KEY',
]);

if ($response->successful()) {
    file_put_contents($outputPath, $response->body());
}
  • Replace YOUR_REMOVE_BG_API_KEY with your API key.
  • $pathToUploadedImage is the path to your uploaded image.
  • $outputPath is where you want to save the PNG with the background removed.

2. Using Spatie's Media Library with Remove.bg

If you're using spatie/laravel-medialibrary, you can create a custom conversion that uses the Remove.bg API.

3. Using Python Scripts (Advanced)

If you want a free, open-source solution and have control over your server, you can use Python libraries like rembg. You'd need to call a Python script from PHP.

Example shell command:

exec("rembg input.jpg output.png");

You can use Laravel's Process or exec() to run this command after validating and saving the uploaded image.

4. Using ImageMagick (Limited)

If your images have a pure white background, you can use ImageMagick's convert command to make white pixels transparent:

exec("convert input.jpg -fuzz 10% -transparent white output.png");
  • -fuzz 10% allows for some tolerance in what is considered "white".

Summary

  • Intervention/Image is not suitable for background removal.
  • Remove.bg API is the easiest and most accurate for most use cases.
  • rembg (Python) is a free, open-source alternative if you can run Python scripts.
  • ImageMagick can work for simple cases with pure white backgrounds.

Let me know if you need a more detailed implementation for any of these options!

vincent15000's avatar

Have you read my comment 3 days ago ? Just above your comment. ;)

1 like

Please or to participate in this conversation.