MEDIA GUIDES / Image Effects

How to Remove a Background from an Image with PHP

If you’ve ever needed to remove background from images with PHP, you’ll know how frustrating it can be to do it manually.. Traditional methods involve desktop tools, plugins, or complex libraries that don’t scale well. With Cloudinary, you can do it in just a few lines of PHP, letting you focus on your app instead of image editing.

In this tutorial, we’ll walk through everything step by step:

Setting Up Your Project

First things first: we need a development environment to run our PHP server locally. You can use a PHP server like XAMPP or MAMP. For this tutorial, we will be using XAMPP, which is a free, easy-to-install Apache distribution with a development environment. We’ll also need Composer (a dependency manager for PHP) to install the Cloudinary SDK.

Once Composer is ready, navigate to the htdocs folder in your XAMPP installation and create a new project folder using your terminal:

mkdir remove-bg-demo
cd remove-bg-demo

Installing Cloudinary PHP SDK

The next step is to add the Cloudinary SDK to your project so you can interact with the Cloudinary API from PHP. To do this, open up your terminal in the project directory and run the following command:

composer require cloudinary/cloudinary_php

This should download and install the Cloudinary PHP SDK into your project. Composer will create a vendor folder containing the SDK and an autoload.php file, which we’ll use later to include the library in our PHP files.

Uploading Images to Cloudinary

Before we can remove an image’s background, we first need to upload it to Cloudinary. So, start by logging into your Cloudinary account. If you don’t have one, sign up for free.

Before uploading our image, log in to your Cloudinary account, navigate to the Dashboard tab, and click the Go to API Keys button. This is where you’ll find your Cloud Name, API Key, and API Secret. These credentials will allow your PHP project to connect securely to Cloudinary.

Now to upload your image, simply open up the Assets tab and drag and drop an image (for example, a product photo or profile picture), and Cloudinary will assign it a unique public ID.

How to Remove Background from Images with PHP using Cloudinary

Now that we have an image stored in Cloudinary, we can apply the background removal transformation.

Cloudinary provides a simple effect called background_removal. With just a single transformation, the background of the uploaded image can be stripped away, leaving the subject on a transparent background.

Applying A Background Removal Effect

To remove the background of our image, let’s start by creating a new file named remove_image.php in your project directory and importing the Cloudinary PHP SDK:

<?php
require 'vendor/autoload.php';

use Cloudinary\Cloudinary;

Next, we will configure our API using the Cloudinary SDK:

$cloudinary = new Cloudinary([
    'cloud' => [
        'cloud_name' => 'CLOUD_NAME',
        'api_key'    => 'API_KEY',
        'api_secret' => 'API_SECRET'
    ]
]);

Remember to replace my_key, my_secret, and my_cloud_name with your actual API credentials. Alternatively, you can set these credentials as environment variables.

Next, we will call the image() method to load our image, and subsequently remove its background using effect(). We also add in a format('png') parameter, which ensures the background is transparent, making it easy to layer the subject onto new backgrounds. Here is what our complete code looks like:

<?php
require 'vendor/autoload.php';

use Cloudinary\Cloudinary;

$cloudinary = new Cloudinary([
    'cloud' => [
        'cloud_name' => 'CLOUD_NAME',
        'api_key'    => 'API_KEY',
        'api_secret' => 'API_SECRET'
    ]
]);

$url = $cloudinary->image('woman-business-suit_m8gqnw')
    ->effect(Effect::backgroundRemoval())
    ->format('png')
    ->toUrl();

echo '<img src="' . $url . '" alt="Background removed" />';
?>

Running the Transformation

Now that we have everything set up, all we need to do is run our PHP script. Start by opening up your XAMPP control panel and starting your Apache server:

As you can see, our server is running on ports 80 and 443. Next, open up your browser and navigate to http://localhost/remove-bg-demo. This will take you to your project’s index page:

Now, you just need to run your PHP file by clicking on it. Here is what your output should look like:

At this stage, your PHP application is capable of automatically removing backgrounds from images. The format('png') converts the image into a PNG, ensuring you get a transparent output, making it easier to layer the subject onto new backgrounds or use it in design templates.

Because Cloudinary handles everything in the cloud, the transformation happens quickly, and the results are cached at the CDN edge for fast delivery in subsequent requests.

Combining with Other Effects

Background removal doesn’t have to be the final step. Once you’ve removed an image’s background, you can apply additional transformations to create polished, ready-to-use assets.

Adding Overlays or New Backgrounds

If you want your subject to stand out against a colored background, you can easily replace the removed background with a solid color:

$url = $cloudinary->image('woman-business-suit_m8gqnw')
    ->effect(Effect::backgroundRemoval())
    ->background('lightblue')
    ->toUrl();

Here, we remove the background and replace it with a solid light blue background in a single transformation chain. Here is what our image looks like:

Chaining Transformations in PHP

Cloudinary also lets you chain multiple transformations together. For example, you might want to remove the background and then add a drop shadow for extra depth:

$url = $cloudinary->image('woman-business-suit_m8gqnw')
    ->effect(Effect::backgroundRemoval())   
    ->effect(Effect::shadow())
    ->format('png')
    ->toUrl();

This code applies two effects in sequence – first background removal, then a shadow effect – showing how easy it is to stack transformations in PHP:

The Wrap-Up

And that’s all it takes to remove background from images with PHP. Instead of wrestling with heavy image-processing libraries or manual editing, Cloudinary’s SDK turns this into a few lines of code. Once your image is uploaded, you can instantly strip away the background, deliver it as a transparent PNG or WebP, and even layer on new effects like shadows, overlays, or color fills.

The real power here is scalability. Whether you’re cleaning up a single profile picture or processing thousands of product shots for an e-commerce site, the same workflow applies. And Cloudinary handles all the transformation and delivery in the cloud. That means you can focus on building features while Cloudinary takes care of performance, optimization, and speed.

Create a free Cloudinary account and see how much faster background editing can be!

Frequently Asked Questions

How do I remove background from images with PHP in bulk?

Yes, you can batch upload images to Cloudinary and apply the background removal transformation to all of them programmatically.

What output formats are supported after background removal?

You can deliver images as PNG, WebP, or even JPEG. PNG and WebP preserve transparency, which is ideal if you plan to add your own custom backgrounds later.

Does background removal slow down delivery?

No, Cloudinary caches transformed versions at the CDN edge. Once generated, the background-removed image is delivered as quickly as any other optimized Cloudinary asset.

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better remove and manage backgrounds in PHP applications using Cloudinary:

  1. Use Cloudinary upload presets to streamline workflows
    Define an upload preset that automatically applies background removal and other transformations upon upload. This removes the need to call transformations later in your PHP logic.
  2. Leverage eager transformations for performance
    When uploading, set eager transformations that pre-generate the background-removed image. This avoids first-load delays by ensuring the transformed version is instantly available via CDN.
  3. Tag assets with metadata for tracking transformations
    Add descriptive tags when uploading (e.g., bg_removed, profile_photo) so you can later query or manage assets efficiently through Cloudinary’s Admin API.
  4. Use AI-based auto-tagging to inform transformation decisions
    Combine Cloudinary’s auto-tagging with PHP logic to apply background removal only when relevant subjects (e.g., people, products) are detected—saving transformation quota.
  5. Integrate fallback images for failed background removal
    Implement logic to detect whether the background removal succeeded (e.g., by checking alpha channel) and revert to the original image or a default fallback when necessary.
  6. Batch transform with the Admin API and asynchronous workflows
    For large-scale operations, use the Admin API to queue background removal transformations asynchronously and poll for completion—especially helpful for bulk jobs.
  7. Apply contour-aware cropping after background removal
    Combine background removal with Cloudinary’s gravity:auto and crop:pad or crop:fill to tightly frame subjects while preserving composition.
  8. Store public IDs based on hashes or UUIDs
    Use deterministic or random unique IDs for uploaded assets to prevent filename collisions and simplify updates, especially in user-generated content workflows.
  9. Cache transformation URLs in a CDN layer
    If you apply dynamic transformations frequently, cache the final URLs in your app or a CDN edge layer (e.g., Cloudflare) to offload repeated transformation hits.
  10. Create reusable PHP helper functions for transformations
    Encapsulate transformation logic in helper functions or a service class so your code stays DRY and consistent across different parts of your application.
Last updated: Nov 7, 2025