Upgrade from Remove.bg to Picsart's Remove Background API

Learn how to switch from Remove.bg to Picsart's Remove Background API, leveraging enhanced features for more precise and customizable image processing. Ideal for developers looking to improve workflow and output quality in their projects.

Transitioning from Remove.bg to Picsart's Remove Background API offers you an array of advanced features for enhancing your image processing workflows. This article will guide you through the migration process, detailing the similarities and additional capabilities provided by Picsart, to ensure a smooth transition for your projects.

Understanding the Basics

Both Remove.bg and Picsart provide robust solutions for removing backgrounds from images, but Picsart offers expanded functionality to better tailor the results to your specific needs. While the basic premise of sending an HTTP POST request to remove the background remains the same, switching to Picsart opens up new possibilities with additional parameters and customization options.

Code Example for Remove.bg *

Here's how a typical API call looks like with Remove.bg:

curl -H 'x-api-key: YOUR_REMOVE_BG_API_KEY' \
     -H 'Accept: application/json' \
     -F 'image_file=@/path/to/file.jpg' \
     -F 'crop=true' \
     -F 'bg_color=FFFFFF' \
     -F 'format=jpg' \
     -f 
     -X POST https://api.remove.bg/v1.0/removebg

This command sends an image file to Remove.bg, specifying the image should be cropped and setting the background color to be white and the output format to be JPG.

Transitioning to Picsart's Remove Background API

Migrating to Picsart not only involves changing the API endpoint but also taking advantage of additional parameters that enhance your control over the background removal process. Here's how you can adapt the above Remove.bg API call to use Picsart’s API:

curl -H 'X-Picsart-API-Key: YOUR_PICSART_API_KEY' \
     -H 'Accept: application/json' \
     -H 'Content-Type: multipart/form-data' \
     -F 'image=@/path/to/file.jpg' \
     -F 'output_type=cutout' \
     -F 'bg_color=FFFFFF' \
     -F 'format=JPG' \
     -f
     -X POST https://api.picsart.io/tools/1.0/removebg

In this updated API call for Picsart:

  • output_type=cutout aligns with crop=true in Remove.bg, focusing on extracting the main subject of the image.
  • Additional parameters like bg_color, auto_center, scale, and format can be added, and they will give you more control over the final output.

Additional Features and Parameters in Picsart's API

Picsart's Remove Background API supports a wider range of parameters allowing more refined control over how backgrounds are removed. This table highlights the functional similarities and exclusive features of both APIs, helping users understand how to map parameters when migrating from one service to another.

Feature

Remove.bg parameter

Description

Picsart parameter

Description

Source Image File

image_file

Source image file (binary). (If this parameter is present, the other image source parameters must be empty.)

image

Source image file (binary).

image_file_b64

Source image file (base64-encoded string). (If this parameter is present, the other image source parameters must be empty.)

(not supported)

N/A

Source Image URL

image_url

Source image URL. (If this parameter is present, the other image source parameters must be empty.)

image_url

Source image URL.

Image Format

format

Result image format options: auto, png, jpg, zip.

format

Select from JPG, PNG, WEBP; defaults to PNG. ZIP is not supported.

Output Resolution

size

Maximum output image resolution options like preview, full, 50MP, auto.

bg_width
bg_height

Size, in pixels, for the width and height granular control. If left blank, the background is left at its original width.

Foreground Type

type

Foreground type options: auto, person, product, car.

(not supported)

The foreground type is autodetected.

Classification

type_level

Classification level of detected foreground type.

(not supported)

Crop

crop

Whether to crop off all empty regions.

(not supported)

Picsart does not trim down to the cropped, cutout object. Instead the bg_height, bg_width can be used together with scale and auto_center to get the best result.

Crop Margin

crop_margin

Adds a margin around the cropped subject.

(not supported)

Scale

scale

Scales the subject relative to the total image size.

scale

Fit or fill the background. Default: fit.

Position

position

Positions the subject within the image canvas.

auto_center

Automatically center the object, for cutouts only.

Background Color

bg_color

Adds a solid color background.

bg_color

Background color, supports hex codes and names.

Background Image

bg_image_url

Adds a background image from a URL.

bg_image_url

Adds a background image from a URL.

bg_image_file

Adds a background image from a file (binary).

bg_image

Background image file for cutouts.

Background Blur

(not supported)

bg_blur

Apply blur to the background, integer values from 0 to 100.

Background Width

(not supported)

bg_width

Width of the background in pixels.

Background Height

(not supported)

bg_height

Height of the background in pixels.

Semitransparency

semitransparency

Whether to have semi-transparent regions in the result.

(not supported)

Add Shadow

add_shadow

Whether to add an artificial shadow to the result.

(coming soon)

Add Stroke

(not supported)

stroke_size

The size of a solid stroke (border) around the cutout result.

(not supported)

stroke_color

The color of the stroke added to the cutout result.

(not supported)

stroke_opacity

The opacitiy of the stroke added to the cutout result.

Channels

channels

Request either the finalized image (rgba) or an alpha mask (alpha).

output_type

Select one of the two output options. cutout matches rgba and mask matches alpha.

Region of Interest

roi

Region of interest: Specifies a region in the image to detect as foreground.

Handling the response

Example of Remove.bg response

When migrating from Remove.bg to Picsart, it's important to note the differences in supported response content types. Remove.bg offers flexibility in response formats; it can return the processed image directly as a binary file or a base64-encoded string within a JSON object. This allows developers to choose whether to immediately display the image or process the JSON response for additional data like image dimensions and positioning.

{
  "data": {
    "result_b64": "iVBORw0KGgoAAAANSUhEUgAAAIsAAACFC...",
    "foreground_top": 0,
    "foreground_left": 0,
    "foreground_width": 100,
    "foreground_height": 100
  }
}

This response includes a file encoded as a base64 string within the JSON.

Picsart's response

Conversely, Picsart standardizes its responses by consistently returning them in JSON format. This uniform approach ensures that responses are predictable and structured, facilitating easier data handling and integration into applications. When using Picsart's API, developers can expect a JSON response containing URLs and status information, which provides a reliable and consistent method for accessing and using the processed image data. This difference emphasizes the need for adaptations in response handling mechanisms when migrating between these services.

{
  "status": "success",
  "data": {
    "id": "e7bd38.....b1593.png",
    "url": "https://cdn.picsart.io/e7bd38...b1593.png"
  }
}

Below is a comparison table that outlines the differences in response formats from the Picsart and Remove.bg APIs, along with a step-by-step guide on how to handle the migration when dealing with these responses.

Response Comparison Table

FeatureRemove.bg ResponsePicsart Response
ID(not supported)"id": "string"
URL(not supported)"url": "string"
Base64 Image"result_b64": "base64_encoded_string"(not supported)
Foreground Position"foreground_top": 0, "foreground_left": 0(not supported)
Foreground Dimensions"foreground_width": 100, "foreground_height": 100(not supported)
Status(not supported)"status": "string"

Migrate Response Handling

1. Understanding Response Structure Differences

Begin by reviewing the differences in response structure outlined in the table above. Note that Picsart provides a URL directly, whereas Remove.bg may provide the file for a download or a base64 encoded string of the image.

2. Adjust Response Parsing Logic

  • If your application currently handles Remove.bg’s response by decoding the base64 image, you will need to adjust it to directly utilize the URL provided by Picsart for displaying or processing the image.
  • Check for the presence of the "url" key in the Picsart response and use it directly in your image tags or processing logic.
import base64
from PIL import Image
from io import BytesIO

def save_base64_image(b64_string, output_file):
    """
    Decodes a base64 encoded image and saves it to a file.
    
    Args:
    - b64_string (str): The base64 encoded string of the image.
    - output_file (str): The filepath where the image will be saved.
    """
    # Decode the base64 string to bytes
    image_data = base64.b64decode(b64_string)
    
    # Convert bytes data to a PIL Image object
    image = Image.open(BytesIO(image_data))
    
    # Save the image
    image.save(output_file)

# Example Usage
base64_string = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
save_base64_image(base64_string, 'output_image.png')

This code will need to change to

import requests
import json

def download_image_from_json(json_string, output_file):
    """
    Parses a JSON string to extract an image URL and downloads the image.
    
    Args:
    - json_string (str): JSON string containing the image URL.
    - output_file (str): File path where the image will be saved.
    """
    # Convert JSON string into a Python dictionary
    data = json.loads(json_string)
    
    # Check if the status is 'success' and if URL is present
    if data.get('status') == 'success' and 'url' in data.get('data', {}):
        # Get the URL from the JSON data
        url = data['data']['url']
        
        # Send a GET request to the URL
        response = requests.get(url)
        
        # Check if the request was successful
        if response.status_code == 200:
            # Open a file in binary write mode and save the image data
            with open(output_file, 'wb') as file:
                file.write(response.content)
            print("Image downloaded and saved successfully.")
        else:
            print("Failed to download the image. HTTP Status Code:", response.status_code)
    else:
        print("Invalid JSON data or status is not 'success'.")

# Example usage
json_string = '{"status": "success", "data": {"url": "https://cdn.picsart.io/e7bd38...b1593.png"}}'
download_image_from_json(json_string, 'downloaded_image.jpg')

3. Handle Foreground Positioning and Dimensions

  • If your application uses specific foreground positioning and dimensions from Remove.bg, you may need to implement additional logic to handle this as Picsart does not provide these details in the response.
  • Consider implementing image processing functionalities on your end if precise control over image dimensions and cropping is required.

4. Update Error Handling

  • Adapt your error handling mechanisms to account for the "status" field in the Picsart response to manage different states of the response effectively.
  • Ensure that your application can gracefully handle any errors or unusual responses by checking the "status" field before proceeding with further processing.

5. Testing and Validation

  • Thoroughly test the new implementation with a variety of images to ensure that the Picsart API meets all your application's requirements and that the image handling logic works correctly across all expected scenarios.
  • Validate that all functionalities that depend on the image processing are still performing as expected after the migration.

6. Documentation and Training

  • Update any internal and external documentation to reflect changes in the API usage and response handling.
  • Train your team on the new system specifics, especially focusing on differences in how responses are handled and any new error management procedures.

Benefits of Migrating to Picsart

Switching to Picsart’s API can enhance your application’s capabilities with:

  • Advanced image processing features that allow more customization.
  • Greater control over output settings which can lead to better integration into your existing systems or workflows.

That's All

Migrating from Remove.bg to Picsart's Remove Background API is not only straightforward but also beneficial, providing advanced features and greater flexibility. By utilizing the detailed parameters and options that Picsart offers, you can elevate the quality of your background removal tasks and tailor the outputs more closely to your project's requirements.

*Please note that the code examples and API documentation for remove.bg provided here were last verified as of May 1st, 2024. The original documentation and services may have undergone changes since the publication of this article.