Alpha Matte

The Alpha Channel Output provides detailed transparency data. It's great for image compositing, graphical enhancements, and precise background manipulation.

Image as Input, Alpha as Output
Image as Input, Alpha Matte as Output

Base64 Request & Response

Integrate detailed transparency data directly within web structures or JSON payloads with a Base64-encoded image in a JSON object.

import requests

def get_alpha_matte(image_base64, api_key):
    url = "https://api.withoutbg.com/v1.0/alpha-channel-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 = get_alpha_matte(image_base64, api_key)
    print(result)
except Exception as e:
    print(f"An error occurred: {e}")


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class ImageBackgroundRemoval {

    public static String getAlphaMatte(String imageBase64, String apiKey) throws Exception {
        String urlString = "https://api.withoutbg.com/v1.0/alpha-channel-base64";
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("X-API-Key", apiKey);
        conn.setDoOutput(true);

        JSONObject jsonInput = new JSONObject();
        jsonInput.put("image_base64", imageBase64);

        try(OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonInput.toString().getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode);
        }

        StringBuilder response = new StringBuilder();
        try(BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        }

        conn.disconnect();

        JSONObject jsonResponse = new JSONObject(response.toString());
        return jsonResponse.getString("alpha_base64");
    }

    public static void main(String[] args) {
        try {
            String apiKey = "YOUR_API_KEY";
            String imageBase64 = "/9j/4AAQSkZJRgABAQAAA..."; // Replace with your base64-encoded image string
            String alphaMatte = getAlphaMatte(imageBase64, apiKey);
            System.out.println("Alpha Matte: " + alphaMatte);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


<<php

function getAlphaMatte($imageBase64, $apiKey) {
    $url = "https://api.withoutbg.com/v1.0/alpha-channel-base64";

    $headers = array(
        'Content-Type: application/json',
        'X-API-Key: ' . $apiKey,
    );

    $postData = json_encode(array('image_base64' => $imageBase64));

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception(curl_error($ch));
    }

    $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($httpStatusCode != 200) {
        throw new Exception("Response with Status Code: " . $httpStatusCode);
    }

    curl_close($ch);

    $decodedResponse = json_decode($response, true);
    return $decodedResponse['alpha_base64'];
}

// Example usage
$apiKey = 'YOUR_API_KEY';
$imageBase64 = '/9j/4AAQSkZJRgABAQAAA...'; // Replace with your base64-encoded image string

try {
    $alphaMatte = getAlphaMatte($imageBase64, $apiKey);
    echo "Alpha Matte: " . $alphaMatte;
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}
?>


use reqwest;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::error::Error;

#[derive(Serialize)]
struct RequestBody {
    image_base64: String,
}

#[derive(Deserialize)]
struct ResponseBody {
    alpha_base64: String,
}

async fn get_alpha_matte(image_base64: String, api_key: String) -> Result<String, Box<dyn Error>> {
    let client = reqwest::Client::new();
    let url = "https://api.withoutbg.com/v1.0/alpha-channel-base64";
    let body = RequestBody { image_base64 };

    let response = client.post(url)
        .header("Content-Type", "application/json")
        .header("X-API-Key", api_key)
        .json(&body)
        .send()
        .await?;

    if response.status().is_success() {
        let parsed_response = response.json::<ResponseBody>().await?;
        Ok(parsed_response.alpha_base64)
    } else {
        Err(format!("Error: HTTP {}", response.status()).into())
    }
}

// Example usage (this needs to be inside an async context or runtime)
#[tokio::main]
async fn main() {
    let api_key = "YOUR_API_KEY".to_string();
    let image_base64 = "/9j/4AAQSkZJRgABAQAAA...".to_string(); // Replace with your base64-encoded image string

    match get_alpha_matte(image_base64, api_key).await {
        Ok(alpha_matte) => println!("Alpha Matte: {}", alpha_matte),
        Err(e) => eprintln!("An error occurred: {}", e),
    }
}


const axios = require('axios');

async function getAlphaMatte(imageBase64, apiKey) {
    const url = "https://api.withoutbg.com/v1.0/alpha-channel-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 });

        if (response.status === 200) {
            return response.data;
        } else {
            throw new Error(`API request failed with status code ${response.status}`);
        }
    } catch (error) {
        throw new Error(`An error occurred while making the API request: ${error.message}`);
    }
}

// Example usage
const apiKey = "YOUR_API_KEY";
const imageBase64 = "/9j/4AAQSkZJRgABAQAAA..."; // Replace with your base64-encoded image string

getAlphaMatte(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"
)

type RequestData struct {
    ImageBase64 string `json:"image_base64"`
}

type ResponseData struct {
    AlphaBase64 string `json:"alpha_base64"`
}

func getAlphaMatte(imageBase64 string, apiKey string) (string, error) {
    url := "https://api.withoutbg.com/v1.0/alpha-channel-base64"

    requestData := RequestData{
        ImageBase64: imageBase64,
    }

    jsonReq, err := json.Marshal(requestData)
    if err != nil {
        return "", err
    }

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonReq))
    if err != nil {
        return "", err
    }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-API-Key", apiKey)

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return "", fmt.Errorf("API request failed with status code: %d", resp.StatusCode)
    }

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }

    var responseData ResponseData
    err = json.Unmarshal(body, &responseData)
    if err != nil {
        return "", err
    }

    return responseData.AlphaBase64, nil
}

func main() {
    apiKey := "YOUR_API_KEY"
    imageBase64 := "/9j/4AAQSkZJRgABAQAAA..." // Replace with your base64-encoded image string

    alphaMatte, err := getAlphaMatte(imageBase64, apiKey)
    if err != nil {
        fmt.Println("An error occurred:", err)
    } else {
        fmt.Println("Alpha Matte:", alphaMatte)
    }
}


curl --request POST \
  --url https://api.withoutbg.com/v1.0/alpha-channel-base64 \
  --header 'Content-Type: application/json' \
  --header 'X-API-Key: YOUR_API_KEY' \
  --data '{
  "image_base64": "/9j/4AAQSkZJRgABAQAA..."
}'

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class ImageProcessor
{
    private readonly HttpClient _httpClient;

    public ImageProcessor(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> GetAlphaMatteAsync(string imageBase64, string apiKey)
    {
        var url = "https://api.withoutbg.com/v1.0/alpha-channel-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);
            response.EnsureSuccessStatusCode();

            var responseContent = await response.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<dynamic>(responseContent);
            return result.alpha_base64;
        }
        catch (HttpRequestException e)
        {
            throw new Exception($"Error making API request: {e.Message}");
        }
    }
}

// Example usage
public async Task ExampleUsageAsync()
{
    var httpClient = new HttpClient();
    var imageProcessor = new ImageProcessor(httpClient);

    string apiKey = "YOUR_API_KEY";
    string imageBase64 = "/9j/4AAQSkZJRgABAQAAA...";  // Replace with your base64-encoded image string

    try
    {
        string alphaMatte = await imageProcessor.GetAlphaMatteAsync(imageBase64, apiKey);
        Console.WriteLine("Alpha Matte: " + alphaMatte);
    }
    catch (Exception e)
    {
        Console.WriteLine("An error occurred: " + e.Message);
    }
}


Sample Response:

{
  "alpha_base64": "iVBORw0KGgoAAAANSUhEUg..."
}

Binary Request & Response

Suitable for local processing, get a binary PNG file.

import requests

def get_alpha_matte_from_file(file_path, api_key):
    url = "https://api.withoutbg.com/v1.0/alpha-channel"
    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("alpha-matte.png", "wb") as out_file:
                out_file.write(response.content)
            return "Alpha matte saved as alpha-matte.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 = get_alpha_matte_from_file(file_path, api_key)
    print(result)
except Exception as e:
    print(f"An error occurred: {e}")


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

public class ImageBackgroundRemoval {

    public static String getAlphaMatteFromFile(String filePath, String apiKey) throws IOException {
        String url = "https://api.withoutbg.com/v1.0/alpha-channel";
        String boundary = UUID.randomUUID().toString();
        byte[] boundaryBytes = ("--" + boundary + "\r\n").getBytes("UTF-8");
        byte[] finishBoundaryBytes = ("--" + boundary + "--").getBytes("UTF-8");
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

        // Set up the body
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setRequestProperty("X-API-Key", apiKey);

        try (OutputStream output = connection.getOutputStream()) {
            // File
            output.write(boundaryBytes);
            String fileHeader = "Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath + "\"\r\n" +
                                "Content-Type: application/octet-stream\r\n\r\n";
            output.write(fileHeader.getBytes("UTF-8"));
            Files.copy(Paths.get(filePath), output);
            output.write("\r\n".getBytes("UTF-8"));

            // End of multipart/form-data
            output.write(finishBoundaryBytes);
        }

        // Get the response
        int status = connection.getResponseCode();
        InputStream in = (status == HttpURLConnection.HTTP_OK) ? connection.getInputStream() : connection.getErrorStream();

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        for (int length; (length = in.read(buffer)) != -1; ) {
            result.write(buffer, 0, length);
        }

        // Save the output if successful
        if (status == HttpURLConnection.HTTP_OK) {
            try (FileOutputStream fos = new FileOutputStream("alpha-matte.png")) {
                fos.write(result.toByteArray());
            }
            return "Alpha matte saved as alpha-matte.png";
        } else {
            throw new IOException("API request failed with status code " + status + ": " + result.toString("UTF-8"));
        }
    }

    public static void main(String[] args) {
        String apiKey = "YOUR_API_KEY";
        String filePath = "input-image.jpg"; // Replace with your image file path

        try {
            String result = getAlphaMatteFromFile(filePath, apiKey);
            System.out.println(result);
        } catch (IOException e) {
            System.err.println("An error occurred: " + e.getMessage());
        }
    }
}


<?php

function getAlphaMatteFromFile($filePath, $apiKey) {
    $url = "https://api.withoutbg.com/v1.0/alpha-channel";

    // Initialize cURL session
    $curl = curl_init();

    // Set cURL options
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "X-API-Key: " . $apiKey,
    ));

    // Define the file to be sent
    $cfile = curl_file_create($filePath);

    // Set POST fields
    $postData = array(
        'file' => $cfile,
    );
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);

    // Execute cURL session and get the response
    $response = curl_exec($curl);
    $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    // Close cURL session
    curl_close($curl);

    // Check the response status
    if ($status_code == 200) {
        // Save the output as a file
        file_put_contents("alpha-matte.png", $response);
        return "Alpha matte saved as alpha-matte.png";
    } else {
        throw new Exception("API request failed with status code $status_code: $response");
    }
}

// Example usage
$apiKey = "YOUR_API_KEY";
$filePath = "input-image.jpg"; // Replace with your image file path

try {
    $result = getAlphaMatteFromFile($filePath, $apiKey);
    echo $result;
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}

?>


use reqwest::Client;
use std::fs::File;
use std::io::Read;
use reqwest::multipart::{Form, Part};
use std::error::Error;

async fn get_alpha_matte_from_file(file_path: &str, api_key: &str) -> Result<(), Box<dyn Error>> {
    let url = "https://api.withoutbg.com/v1.0/alpha-channel";

    // Open the file
    let mut file = File::open(file_path)?;
    let mut file_contents = Vec::new();
    file.read_to_end(&mut file_contents)?;

    // Create the form
    let form = Form::new()
        .part("file", Part::bytes(file_contents).file_name(file_path.to_string()));

    // Make the request
    let client = Client::new();
    let res = client.post(url)
        .header("X-API-Key", api_key)
        .multipart(form)
        .send()
        .await?;

    if res.status().is_success() {
        let content = res.bytes().await?;
        std::fs::write("alpha-matte.png", &content)?;
        println!("Alpha matte saved as alpha-matte.png");
    } else {
        return Err(format!("API request failed with status code {}", res.status()).into());
    }

    Ok(())
}

#[tokio::main]
async fn main() {
    let api_key = "YOUR_API_KEY";
    let file_path = "input-image.jpg"; // Replace with your image file path

    if let Err(e) = get_alpha_matte_from_file(file_path, api_key).await {
        eprintln!("An error occurred: {}", e);
    }
}


const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

async function getAlphaMatteFromFile(filePath, apiKey) {
  const url = 'https://api.withoutbg.com/v1.0/alpha-channel';
  const headers = {
    'X-API-Key': apiKey,
  };

  try {
    const formData = new FormData();
    formData.append('file', fs.createReadStream(filePath));

    const response = await axios.post(url, formData, {
      headers: {
        ...formData.getHeaders(),
        ...headers,
      },
      responseType: 'arraybuffer'
    });

    if (response.status === 200) {
      // To save the output as a file
      fs.writeFileSync('alpha-matte.png', response.data);
      return 'Alpha matte saved as alpha-matte.png';

      // Alternatively, return the binary content
      // return response.data;
    } 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

getAlphaMatteFromFile(filePath, apiKey)
  .then(result => console.log(result))
  .catch(error => console.error(`An error occurred: ${error}`));


package main

import (
    "bytes"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "os"
)

func getAlphaMatteFromFile(filePath string, apiKey string) (string, error) {
    url := "https://api.withoutbg.com/v1.0/alpha-channel"

    // Prepare the file to be uploaded
    file, err := os.Open(filePath)
    if err != nil {
        return "", err
    }
    defer file.Close()

    // Create a new multipart writer
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    part, err := writer.CreateFormFile("file", filePath)
    if err != nil {
        return "", err
    }
    _, err = io.Copy(part, file)
    if err != nil {
        return "", err
    }
    writer.Close()

    // Create a new request with the multipart body
    req, err := http.NewRequest("POST", url, body)
    if err != nil {
        return "", err
    }
    req.Header.Set("Content-Type", writer.FormDataContentType())
    req.Header.Set("X-API-Key", apiKey)

    // Perform the request
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    // Handle the response
    if resp.StatusCode == http.StatusOK {
        // Save the response to a file
        outFile, err := os.Create("alpha-matte.png")
        if err != nil {
            return "", err
        }
        defer outFile.Close()

        _, err = io.Copy(outFile, resp.Body)
        if err != nil {
            return "", err
        }
        return "Alpha matte saved as alpha-matte.png", nil
    } else {
        return "", fmt.Errorf("API request failed with status code %d", resp.StatusCode)
    }
}

func main() {
    apiKey := "YOUR_API_KEY"
    filePath := "input-image.jpg" // Replace with your image file path

    result, err := getAlphaMatteFromFile(filePath, apiKey)
    if err != nil {
        fmt.Println("An error occurred:", err)
    } else {
        fmt.Println(result)
    }
}


curl --request POST \
  --url https://api.withoutbg.com/v1.0/alpha-channel \
  --header 'Content-Type: multipart/form-data' \
  --header 'X-API-Key: YOUR_API_KEY' \
  --form file=@/input-image.jpg

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public class ImageBackgroundRemoval
{
    public static async Task<string> GetAlphaMatteFromFileAsync(string filePath, string apiKey)
    {
        var url = "https://api.withoutbg.com/v1.0/alpha-channel";
        using var httpClient = new HttpClient();
        using var form = new MultipartFormDataContent();
        using var fileStream = File.OpenRead(filePath);
        using var streamContent = new StreamContent(fileStream);
        using var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync());

        form.Add(fileContent, "file", Path.GetFileName(filePath));
        httpClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);

        var response = await httpClient.PostAsync(url, form);

        if (response.IsSuccessStatusCode)
        {
            var responseBytes = await response.Content.ReadAsByteArrayAsync();
            await File.WriteAllBytesAsync("alpha-matte.png", responseBytes);
            return "Alpha matte saved as alpha-matte.png";
        }
        else
        {
            throw new Exception($"API request failed with status code {response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
        }
    }

    public static async Task Main(string[] args)
    {
        string apiKey = "YOUR_API_KEY";
        string filePath = "input-image.jpg"; // Replace with your image file path

        try
        {
            var result = await GetAlphaMatteFromFileAsync(filePath, apiKey);
            Console.WriteLine(result);
        }
        catch (Exception e)
        {
            Console.WriteLine($"An error occurred: {e.Message}");
        }
    }
}


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.
413 File size too large. Maximum file size is 10.0 MB
415 Unsupported Media Type. Supported formats are: JPEG, PNG, WebP, TIFF, BMP, GIF.
422 Validation Error.
429 Rate limit (7 request/minute) exceeded