How to Remove Image Backgrounds With the ShortPixel API (cURL, PHP, JavaScript & Python Examples)

Removing the background from one photo is quick. Removing it from hundreds of product photos is not.

That’s where an API comes in. With the ShortPixel API, background removal comes down to adding the bg_remove parameter to a standard optimization request. You can make the background transparent, swap it for a solid color, or place the subject on a different image.

No worries, it’s not complicated. We’ll go through it step by step, with ready-to-use examples.

In this article, we’ll look at how to remove image backgrounds with the ShortPixel API using cURL, PHP, JavaScript, and Python.

What do you need to get started?

Not much. Just two things:

  • A ShortPixel API key. You can find it in your ShortPixel dashboard and in the signup confirmation email. If you don’t have an account yet, you can sign up for free.
  • Your images. They can be online (available through a URL) or stored on your computer or server.

How does background removal work in the ShortPixel API?

Background removal is part of ShortPixel’s Reducer API. It’s the same API that compresses, resizes, and converts your images. You just add the bg_remove parameter to the request.

The parameter accepts three types of values:

  • 1: removes the background and makes it transparent.
  • A URL: removes the background and uses the image from that URL as the new background.
  • #rrggbbxx: replaces the background with a solid color. rrggbb is the hex color code, and xx is the transparency level (00 is fully transparent, FF is fully opaque). For example, #ffffffff gives you a solid white background.

How much does it cost?
Background removal is available on all ShortPixel plans and costs 1 credit per image, so you don’t need a separate add-on. As a general rule, 1 optimized image uses 1 credit too. Keep in mind that generating extra formats also counts: optimizing an image and generating WebP or AVIF versions uses 3 credits.

And there are three endpoints you can use, depending on where your images are:

  • reducer.php: for images that are online. You can send up to 100 URLs in one request.
  • reducer-sync.php: also for online images, but it returns the processed image directly instead of a JSON response.
  • post-reducer.php: for images stored on your computer or server, which you upload with the request.

1. Remove a background with cURL

This is the quickest way to test the API. Open your terminal and run:

curl -X POST https://api.shortpixel.com/v2/reducer.php \
  -H "Content-Type: application/json" \
  -d '{
    "key": "YOUR_API_KEY",
    "plugin_version": "MY123",
    "lossy": 1,
    "wait": 30,
    "bg_remove": "1",
    "urllist": ["https://example.com/images/product.jpg"]
  }'

Here’s what the parameters do:

  • key: your API key.
  • plugin_version: a code you choose for your app (maximum 5 alphanumeric characters).
  • lossy: the compression type (1 for lossy, 2 for glossy, 0 for lossless).
  • wait: how many seconds (1 to 30) the API should wait for the image to be ready before responding.
  • bg_remove: the background option, in this case a transparent background.
  • urllist: the list of image URLs to process.

Want a white background instead? Just change the bg_remove value:

"bg_remove": "#ffffffff"

Or use another image as the background:

"bg_remove": "https://example.com/backgrounds/studio.jpg"

Get the image directly with the sync endpoint

If you don’t want to deal with JSON and a second download step, use the synchronous endpoint. It sends back the processed image, so you can save it straight to a file:

curl -X POST https://api.shortpixel.com/v2/reducer-sync.php \
  -H "Content-Type: application/json" \
  -d '{
    "key": "YOUR_API_KEY",
    "plugin_version": "MY123",
    "lossy": 1,
    "bg_remove": "1",
    "url": "https://example.com/images/product.jpg"
  }' \
  -o product-no-bg.png

Notice that this endpoint takes a single url instead of a urllist.

2. Remove a background with PHP

Here’s the same request in PHP:

<?php
$apiKey   = 'YOUR_API_KEY';
$endpoint = 'https://api.shortpixel.com/v2/reducer.php';
$data = json_encode([
    'key'            => $apiKey,
    'plugin_version' => 'MY123',
    'lossy'          => 1,
    'wait'           => 30,
    'bg_remove'      => '1',
    'urllist'        => ['https://example.com/images/product.jpg'],
]);
$ch = curl_init($endpoint);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $data,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Accept: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
]);
$response = curl_exec($ch);
curl_close($ch);
$item = json_decode($response, true)[0];
if ((int) $item['Status']['Code'] === 2) {
    // The image is ready, so we download it
    file_put_contents('product-no-bg.png', file_get_contents($item['LossyURL']));
    echo 'Done!';
} else {
    echo $item['Status']['Code'] . ': ' . $item['Status']['Message'];
}

If you prefer something shorter, ShortPixel also has an official PHP library with a simple, fluent syntax.

3. Remove a background with JavaScript

Here’s an example using fetch in Node.js (version 18 or newer):

const response = await fetch('https://api.shortpixel.com/v2/reducer.php', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    key: 'YOUR_API_KEY',
    plugin_version: 'MY123',
    lossy: 1,
    wait: 30,
    bg_remove: '1',
    urllist: ['https://example.com/images/product.jpg'],
  }),
});
const [item] = await response.json();
if (item.Status.Code === 2) {
  console.log('Processed image:', item.LossyURL);
} else {
  console.log(`${item.Status.Code}: ${item.Status.Message}`);
}

Important: don’t use your API key in JavaScript that runs in the browser. Anyone can see it in the developer tools. Make the request from your server and send only the result to the browser.

Using Node.js? ShortPixel also has an official Node.js SDK, so you don’t have to build the requests manually. It has dedicated helpers like backgroundRemove() for transparent backgrounds and backgroundChange() for replacing the background with a color or an image, and it takes care of polling for you.

import SHORTPIXEL from "@shortpixel-com/shortpixel";
const { ShortPixelClient } = SHORTPIXEL;
const cli = new ShortPixelClient({ apiKey: process.env.SHORTPIXEL_API_KEY });
const src = await cli.backgroundRemove("assets/product.png", { lossy: 1 });
await src.downloadTo("./output");

Install it with npm i @shortpixel-com/shortpixel. The package is ESM-only, and Node 20+ is recommended. For the full walkthrough, see our guide on how to optimize images in Node.js with the ShortPixel SDK.

4. Remove a background with Python

import requests
r = requests.post(
    'https://api.shortpixel.com/v2/reducer.php',
    json={
        'key': 'YOUR_API_KEY',
        'plugin_version': 'MY123',
        'lossy': 1,
        'wait': 30,
        'bg_remove': '1',
        'urllist': ['https://example.com/images/product.jpg'],
    }
)
item = r.json()[0]
if int(item['Status']['Code']) == 2:
    img = requests.get(item['LossyURL'])
    with open('product-no-bg.png', 'wb') as f:
        f.write(img.content)

5. Remove the background from images that aren’t online

What if the image is on your computer or server and doesn’t have a public URL? Then use the post-reducer.phpendpoint and upload the file with your request:

curl -X POST https://api.shortpixel.com/v2/post-reducer.php \
  -F "key=YOUR_API_KEY" \
  -F "plugin_version=MY123" \
  -F "lossy=1" \
  -F "wait=30" \
  -F "bg_remove=1" \
  -F 'file_paths={"file1": "/unique/path/product.jpg"}' \
  -F "file1=@product.jpg"

The file_paths parameter tells the API which file is which. The key (here, file1) must be the same as the name of the uploaded file field. The value can be any string, as long as it’s unique to that file.

Understanding the API response

The API sends back a JSON response with one entry for each image. The most important field is Status, which has a Code and a Message:

  • Code 2: the image is processed, and the download link is in the response.
  • Code 1: the image was scheduled for processing, but it’s not ready yet. Send the same request again after a few seconds.

Background removal is more demanding than regular compression, so it can take longer. Seeing code 1 from time to time is normal. Just send the same request again after a few seconds.

If you uploaded a file with post-reducer.php and got code 1, don’t upload it again, as it would be processed as a new image. Instead, call reducer.php with the OriginalURL from the first response to check the status.

These are the errors you’re most likely to see:

  • -207: invalid parameters for background removal. Check the bg_remove value.
  • -401 / -402: invalid API key.
  • -403: your quota is exceeded. You’ll need a bigger plan or an additional package.
  • -106: the image URL can’t be accessed by ShortPixel’s servers.
  • -111: the file is too big.
  • -404: the optimization queue is full. Try again in a minute.

You’ll find the full list in the API documentation.

A few tips for working with many images

  • Send images in batches. With reducer.php you can process up to 100 URLs in a single request.
  • Use different settings for different images. The paramlist parameter lets you set custom options for each URL in the same request.
  • Replaced an image but kept the same URL? Add “refresh”: 1 so ShortPixel downloads and processes it again. Otherwise, you may get the previously processed version.
  • Combine tasks. You can remove the background, resize, convert to WebP or AVIF, and upscale the image in a single request.
  • Keep track of your images. Anything you add to returndatalist comes back unchanged in the response, so you can easily match the results with your own data (a product ID, for example).

Conclusion

Removing backgrounds doesn’t have to be a manual job. With the bg_remove parameter, a single API request does it for you, whether you have one image or thousands.

Pick the example that fits your project, add your API key, and you’re ready to go. And once your backgrounds are clean, you can use the same API to resize, compress, or upscale your images.

Want to see the results before writing any code?
Try our free online background remover. And if you’re still deciding which service to use, check out our list of the best background removal APIs with PHP examples.

FAQs

Can I replace the background instead of making it transparent?

Yes. Set bg_remove to a hex color like #ffffffff for a solid background, or to an image URL to use that image as the new background.

Does background removal cost extra?

No. It’s included in all plans. An optimized image uses 1 credit, with or without background removal, while generating WebP or AVIF versions at the same time uses 3 credits.

Can I remove the background from images stored on my computer?

Yes. Use the post-reducer.php endpoint to upload the files with your request.

How many images can I process in one request?

With reducer.php, you can send up to 100 URLs per request.

What does status code 1 mean?

It means the image was scheduled for processing, but it isn’t ready yet. Send the same request again after a few seconds to get the result. You can also increase the wait parameter (up to 30 seconds) so the API waits longer before responding.

Can I use the API key directly in my website’s JavaScript?

It’s not a good idea, because anyone can see and copy it. Make the API calls from your server instead.

What happens if I send an invalid bg_remove value?

The API returns error code -207, which means invalid parameters for background removal.

Remove image backgrounds for free!

Easily remove backgrounds, optimize your pictures and generate WebP/AVIF in bulk using the ShortPixel API

Bianca Rus
Bianca Rus
Articles: 54