Created
September 1, 2025 03:12
-
-
Save symisc/f7bc911c6b83f4a2e8d0e6743ae88e1b to your computer and use it in GitHub Desktop.
Programmatically remove backgrounds from input image using the PixLab BG-REMOVE API Endpoint - https://pixlab.io/endpoints/background-remove-api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'json' | |
require 'base64' | |
require 'uri' | |
# 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. | |
uri = URI('https://api.pixlab.io/bgremove') | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
request = Net::HTTP::Post.new(uri.path) | |
form_data = { | |
'key' => 'PIXLAB_API_KEY', # PixLab API Key - Get yours from https://console.pixlab.io/ | |
'file' => File.open('./local_image.png') | |
} | |
request.set_form(form_data, 'multipart/form-data') | |
response = http.request(request) | |
reply = JSON.parse(response.body) | |
if reply['status'] != 200 | |
puts reply['error'] | |
else | |
img_data = 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 | |
begin | |
img_bytes = Base64.decode64(img_data) | |
output_filename = "output_image.#{extension}" | |
File.open(output_filename, "wb") do |f| | |
f.write(img_bytes) | |
end | |
puts "Background Removed Image saved to: #{output_filename}" | |
rescue => e | |
puts "Error saving output image: #{e}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment