Skip to content

Instantly share code, notes, and snippets.

@symisc
Last active September 2, 2025 08:49
Show Gist options
  • Save symisc/5b4661d61b13001a138c60490ac40487 to your computer and use it in GitHub Desktop.
Save symisc/5b4661d61b13001a138c60490ac40487 to your computer and use it in GitHub Desktop.
Remove background programmatically using the PIxLab BGREMOVE API Endpoint - https://pixlab.io/endpoints/background-remove-api
import requests
import json
import base64
import os
# Programmatically remove backgrounds from input images using the PixLab BG-REMOVE API endpoint.
#
# Refer to the official documentation at: https://pixlab.io/endpoints/background-remove-api for the API reference
# guide and more code samples.
# Use POST to upload the image directly from your local folder. If your image is publicly available
# then make a simple GET request with a link to your image.
req = requests.post(
'https://api.pixlab.io/bgremove',
files={
'file': open('./local_image.png', 'rb') # The local image we are going to remove background from
},
data={
'key': 'PIXLAB_API_KEY' # PixLab API Key - Get yours from https://console.pixlab.io/'
}
)
reply = req.json()
if reply['status'] != 200:
print(reply['error'])
else:
imgData = reply['imgData'] # Base64 encoding of the output image
mimetype = reply['mimeType'] # MIME type (i.e image/jpeg, etc.) of the output image
extension = reply['extension'] # File extension (e.g., 'png', 'jpeg')
# Decode base64 and save to disk
try:
img_bytes = base64.b64decode(imgData)
output_filename = f"output_image.{extension}"
with open(output_filename, "wb") as f:
f.write(img_bytes)
print(f"Background Removed Image saved to: {output_filename}")
except Exception as e:
print(f"Error saving output image: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment