On this page
This documentation provides a better experience when you have an API Key.
Transparent Background
The Transparent Background Output is ideal for applications needing image background removal. It produces images with a transparent background, perfect for compositing over different backgrounds. Whether you prefer Base64 or binary input, you'll receive a high-quality PNG image.
Base64 Request and Response
Use this for web-based apps, and get the image as a Base64 string in a JSON object.
import requests
def remove_background(image_base64, api_key):
url = "https://api.withoutbg.com/v1.0/image-without-background-base64"
headers = {
'Content-Type': 'application/json',
'X-API-Key': api_key
}
data = {"image_base64": image_base64}
try:
response = requests.post(url, json=data, headers=headers)
if response.status_code == 200:
return response.json()
else:
raise ConnectionError(f"API request failed with status code {response.status_code}: {response.text}")
except requests.RequestException as e:
raise SystemError(f"An error occurred while making the API request: {e}")
# Example usage
api_key = "YOUR_API_KEY"
image_base64 = "/9j/4AAQSkZJRgABAQAAA..." # Replace with your base64-encoded image string
try:
result = remove_background(image_base64, api_key)
print(result)
except Exception as e:
print(f"An error occurred: {e}")
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class BackgroundRemover {
public static String removeBackground(String imageBase64, String apiKey) throws IOException {
String url = "https://api.withoutbg.com/v1.0/image-without-background-base64";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Adding request header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("X-API-Key", apiKey);
// JSON payload
JSONObject payload = new JSONObject();
payload.put("image_base64", imageBase64);
// Send post request
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(payload.toString());
wr.flush();
}
int responseCode = con.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("API request failed with status code " + responseCode);
}
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static void main(String[] args) {
String apiKey = "YOUR_API_KEY";
String imageBase64 = "/9j/4AAQSkZJRgABAQAAA..."; // Replace with your base64-encoded image string
try {
String result = removeBackground(imageBase64, apiKey);
System.out.println(result);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
<?php
function removeBackground($imageBase64, $apiKey) {
$url = 'https://api.withoutbg.com/v1.0/image-without-background-base64';
$headers = [
'Content-Type: application/json',
'X-API-Key: ' . $apiKey
];
$payload = json_encode(['image_base64' => $imageBase64]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
throw new Exception("API request failed with status code $httpCode: $response");
}
return json_decode($response, true);
}
// Example usage
$apiKey = 'YOUR_API_KEY';
$imageBase64 = '/9j/4AAQSkZJRgABAQAAA...'; // Replace with your base64-encoded image string
try {
$result = removeBackground($imageBase64, $apiKey);
print_r($result);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
use reqwest::header::{HeaderMap, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use std::error::Error;
#[derive(Serialize)]
struct RequestPayload {
image_base64: String,
}
#[derive(Deserialize)]
struct ResponsePayload {
alpha_base64: String,
}
async fn remove_background(image_base64: String, api_key: &str) -> Result<String, Box<dyn Error>> {
let client = reqwest::Client::new();
let url = "https://api.withoutbg.com/v1.0/image-without-background-base64";
let payload = RequestPayload { image_base64 };
let mut headers = HeaderMap::new();
headers.insert("X-API-Key", api_key.parse()?);
headers.insert(CONTENT_TYPE, "application/json".parse()?);
let response = client
.post(url)
.headers(headers)
.json(&payload)
.send()
.await?;
if response.status().is_success() {
let response_payload = response.json::<ResponsePayload>().await?;
Ok(response_payload.alpha_base64)
} else {
Err(format!("API request failed with status code {}", response.status()).into())
}
}
#[tokio::main]
async fn main() {
let api_key = "YOUR_API_KEY";
let image_base64 = "/9j/4AAQSkZJRgABAQAAA..."; // Replace with your base64-encoded image string
match remove_background(image_base64.to_string(), api_key).await {
Ok(result) => println!("Success: {}", result),
Err(e) => println!("An error occurred: {}", e),
}
}
const axios = require('axios');
async function removeBackground(imageBase64, apiKey) {
const url = 'https://api.withoutbg.com/v1.0/image-without-background-base64';
const headers = {
'Content-Type': 'application/json',
'X-API-Key': apiKey
};
const data = {
image_base64: imageBase64
};
try {
const response = await axios.post(url, data, { headers: headers });
return response.data;
} catch (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error(`API request failed with status code ${error.response.status}: ${error.response.data}`);
} else if (error.request) {
// The request was made but no response was received
console.error(`No response received: ${error.request}`);
} else {
// Something happened in setting up the request that triggered an Error
console.error('Error', error.message);
}
throw error;
}
}
// Example usage
const apiKey = 'YOUR_API_KEY';
const imageBase64 = '/9j/4AAQSkZJRgABAQAAA...'; // Replace with your base64-encoded image string
removeBackground(imageBase64, apiKey)
.then(result => console.log(result))
.catch(error => console.error(`An error occurred: ${error}`));
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// RequestPayload struct to hold the base64 image data
type RequestPayload struct {
ImageBase64 string `json:"image_base64"`
}
// RemoveBackground makes an HTTP POST request to the API
func RemoveBackground(imageBase64, apiKey string) (string, error) {
url := "https://api.withoutbg.com/v1.0/image-without-background-base64"
// Create the payload
payload := RequestPayload{
ImageBase64: imageBase64,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return "", err
}
// Create the request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", apiKey)
// Make the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Read the response
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("API request failed with status code %d: %s", resp.StatusCode, string(body))
}
return string(body), nil
}
func main() {
apiKey := "YOUR_API_KEY"
imageBase64 := "/9j/4AAQSkZJRgABAQAAA..." // Replace with your base64-encoded image string
result, err := RemoveBackground(imageBase64, apiKey)
if err != nil {
fmt.Println("An error occurred:", err)
return
}
fmt.Println(result)
}
curl --request POST \
--url https://api.withoutbg.com/v1.0/image-without-background-base64 \
--header 'Content-Type: application/json' \
--header 'X-API-Key: YOUR_API_KEY' \
--data '{
"image_base64": "/9j/4AAQSkZJRgABAQAAA..."
}'
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class BackgroundRemover
{
private readonly HttpClient _httpClient;
public BackgroundRemover(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> RemoveBackgroundAsync(string imageBase64, string apiKey)
{
var url = "https://api.withoutbg.com/v1.0/image-without-background-base64";
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(JsonConvert.SerializeObject(new { image_base64 = imageBase64 }), Encoding.UTF8, "application/json")
};
request.Headers.Add("X-API-Key", apiKey);
try
{
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"API request failed with status code {response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
}
return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
// Handle exceptions
Console.WriteLine($"An error occurred: {ex.Message}");
throw;
}
}
}
// Example usage
public class Program
{
public static async Task Main(string[] args)
{
var httpClient = new HttpClient();
var remover = new BackgroundRemover(httpClient);
var apiKey = "YOUR_API_KEY";
var imageBase64 = "/9j/4AAQSkZJRgABAQAAA..."; // Replace with your base64-encoded image string
try
{
var result = await remover.RemoveBackgroundAsync(imageBase64, apiKey);
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Sample Response:
{
"img_without_background_base64": "iiabVBORGgoAAAANSUhEUgAAASw...."
}
Binary Request & Response
Choose this for local processing; receive a binary PNG file.
import requests
def remove_background_from_file(file_path, api_key):
url = "https://api.withoutbg.com/v1.0/image-without-background"
headers = {'X-API-Key': api_key}
files = {'file': open(file_path, 'rb')}
try:
response = requests.post(url, headers=headers, files=files)
if response.status_code == 200:
# To save the output as a file
with open("output-image.png", "wb") as out_file:
out_file.write(response.content)
return "Image saved as output-image.png"
# Alternatively, return the binary content
# return response.content
else:
raise ConnectionError(f"API request failed with status code {response.status_code}: {response.text}")
except requests.RequestException as e:
raise SystemError(f"An error occurred while making the API request: {e}")
finally:
files['file'].close()
# Example usage
api_key = "YOUR_API_KEY"
file_path = "input-image.jpg" # Replace with your image file path
try:
result = remove_background_from_file(file_path, api_key)
print(result)
except Exception as e:
print(f"An error occurred: {e}")
import java.io.*;
import java.net.*;
import javax.net.ssl.HttpsURLConnection;
public class ImageBackgroundRemover {
public static void removeBackgroundFromFile(String filePath, String apiKey) throws IOException {
String url = "https://api.withoutbg.com/v1.0/image-without-background";
String boundary = Long.toHexString(System.currentTimeMillis()); // Unique boundary
URL apiUrl = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) apiUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("X-API-Key", apiKey);
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
// Sending file data
File file = new File(filePath);
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append("\r\n");
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append("\r\n");
writer.append("\r\n").flush();
Files.copy(file.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append("\r\n").flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append("\r\n").flush();
// Reading the response
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
try (InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream("output-image.png")) {
byte[] buffer = new byte[4096];
int len;
while ((len = in.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
System.out.println("Image saved as output-image.png");
}
} else {
System.out.println("API request failed with status code " + responseCode);
}
connection.disconnect();
}
public static void main(String[] args) {
String apiKey = "YOUR_API_KEY";
String filePath = "input-image.jpg"; // Replace with your image file path
try {
removeBackgroundFromFile(filePath, apiKey);
} catch (IOException e) {
e.printStackTrace();
System.out.println("An error occurred: " + e.getMessage());
}
}
}
<?php
function removeBackgroundFromFile($filePath, $apiKey) {
$url = "https://api.withoutbg.com/v1.0/image-without-background";
// Initialize a cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-Key: ' . $apiKey));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Add the file to the request
$cFile = curl_file_create($filePath);
$data = array('file' => $cFile);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Execute the cURL request and get the response
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status == 200) {
// Save the output as a file
file_put_contents("output-image.png", $response);
return "Image saved as output-image.png";
} else {
// Handle errors
return "API request failed with status code $status: $response";
}
// Close the cURL session
curl_close($ch);
}
// Example usage
$apiKey = "YOUR_API_KEY";
$filePath = "input-image.jpg"; // Replace with your image file path
try {
$result = removeBackgroundFromFile($filePath, $apiKey);
echo $result;
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
?>
use reqwest::Client;
use std::fs::File;
use std::io::Write;
use reqwest::multipart;
use tokio;
#[tokio::main]
async fn main() {
let api_key = "YOUR_API_KEY";
let file_path = "input-image.jpg"; // Replace with your image file path
match remove_background_from_file(file_path, api_key).await {
Ok(_) => println!("Image saved as output-image.png"),
Err(e) => eprintln!("An error occurred: {}", e),
}
}
async fn remove_background_from_file(file_path: &str, api_key: &str) -> Result<(), reqwest::Error> {
let url = "https://api.withoutbg.com/v1.0/image-without-background";
let client = Client::new();
let form = multipart::Form::new()
.file("file", file_path)?;
let response = client.post(url)
.header("X-API-Key", api_key)
.multipart(form)
.send()
.await?;
if response.status().is_success() {
let mut file = File::create("output-image.png")?;
let content = response.bytes().await?;
file.write_all(&content)?;
Ok(())
} else {
Err(reqwest::Error::new(reqwest::StatusCode::from_u16(response.status().as_u16()).unwrap(), false))
}
}
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
async function removeBackgroundFromFile(filePath, apiKey) {
const url = "https://api.withoutbg.com/v1.0/image-without-background";
const formData = new FormData();
formData.append('file', fs.createReadStream(filePath));
const headers = {
'X-API-Key': apiKey,
...formData.getHeaders()
};
try {
const response = await axios.post(url, formData, { headers });
if (response.status === 200) {
// To save the output as a file
fs.writeFileSync("output-image.png", response.data);
return "Image saved as output-image.png";
// Alternatively, you can handle the binary content differently
} else {
throw new Error(`API request failed with status code ${response.status}: ${response.statusText}`);
}
} catch (error) {
throw new Error(`An error occurred while making the API request: ${error.message}`);
}
}
// Example usage
const apiKey = "YOUR_API_KEY";
const filePath = "input-image.jpg"; // Replace with your image file path
removeBackgroundFromFile(filePath, apiKey)
.then(result => console.log(result))
.catch(error => console.error(`An error occurred: ${error.message}`));
package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
)
func removeBackgroundFromFile(filePath, apiKey string) error {
url := "https://api.withoutbg.com/v1.0/image-without-background"
// Prepare the file to be uploaded
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
// Create a buffer to write our multipart form
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
// Create form file
part, err := writer.CreateFormFile("file", filePath)
if err != nil {
return err
}
_, err = io.Copy(part, file)
if err != nil {
return err
}
writer.Close()
// Create and make the request
request, err := http.NewRequest("POST", url, &buffer)
if err != nil {
return err
}
request.Header.Set("Content-Type", writer.FormDataContentType())
request.Header.Set("X-API-Key", apiKey)
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
// Check the response
if response.StatusCode != http.StatusOK {
return fmt.Errorf("API request failed with status code %d", response.StatusCode)
}
// Save the output as a file
output, err := os.Create("output-image.png")
if err != nil {
return err
}
defer output.Close()
_, err = io.Copy(output, response.Body)
if err != nil {
return err
}
fmt.Println("Image saved as output-image.png")
return nil
}
func main() {
apiKey := "YOUR_API_KEY"
filePath := "input-image.jpg" // Replace with your image file path
err := removeBackgroundFromFile(filePath, apiKey)
if err != nil {
fmt.Printf("An error occurred: %s\n", err)
}
}
curl -X 'POST' \
https://api.withoutbg.com/v1.0/image-without-background \
-H 'X-API-Key: YOUR_API_KEY' \
-F 'file=@input-image.jpg' \
-o output-image.png
using System;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;
class ImageBackgroundRemover
{
static readonly HttpClient client = new HttpClient();
public static async Task RemoveBackgroundFromFileAsync(string filePath, string apiKey)
{
string url = "https://api.withoutbg.com/v1.0/image-without-background";
try
{
using (var formData = new MultipartFormDataContent())
{
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
// Add file content to the form data
var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = Path.GetFileName(filePath)
};
formData.Add(fileContent);
// Make the request
var response = await client.PostAsync(url, formData);
if (response.IsSuccessStatusCode)
{
// Save the output as a file
var outputData = await response.Content.ReadAsByteArrayAsync();
File.WriteAllBytes("output-image.png", outputData);
Console.WriteLine("Image saved as output-image.png");
}
else
{
Console.WriteLine($"API request failed with status code {response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
static async Task Main(string[] args)
{
string apiKey = "YOUR_API_KEY";
string filePath = "input-image.jpg"; // Replace with your image file path
await RemoveBackgroundFromFileAsync(filePath, apiKey);
}
}
Status Codes
Status Code | Description |
---|---|
200 | Success |
401 | Invalid API Key |
402 | Insufficient Credit |
403 | Credits Expired. When you top up, any previous credits will become active once more. |
422 | Validation Error. |
429 | Rate limit (7 request/minute) exceeded |