Background Removal
An optimized solution for image background removal
by AnimarMedia
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Background Removal API sample</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css">
</head>
<body>
<main class="container">
<article style="margin-top: 0px; text-align: center;">
<h3>Background Removal API sample</h3>
<p>This API provides foreground segmentation with consequent background removal.</p>
</article>
<label for="file">Select image to upload
<input type="file" id="file" name="file">
</label>
<h4 id="spinner" style="text-align: center;" aria-busy="true" hidden>Processing</h4>
<section id="sectionParsed" hidden>
<label for="parsed">đź’¬ Result image:
<img id="result-image">
</label>
</section>
</main>
</body>
</html>
JavaScript
// Example of using Animar Media background removal.
// For more details visit:
// https://animarmedia.com/cloud-native-ai-built-for-your-business/
// Use 'rapidapi' if you want to try via RapidAPI marketplace.
// For more details visit:
// https://rapidapi.com/animar-prod/api/ai-api-background-removal
const MODE = 'rapidapi'
const OPTIONS = {
rapidapi: {
url: 'https://ai-api-background-removal.p.rapidapi.com/result-from-file',
headers: {
'X-RapidAPI-Key': '20ada658aemshe3b721c1c2a9cb2p1959c1jsndbb3b9effe8a',
'X-RapidAPI-Host': 'ai-api-background-removal.p.rapidapi.com'
}
}
}
document.addEventListener('DOMContentLoaded', function (event) {
const input = document.getElementById('file')
const resultImage = document.getElementById('result-image')
const sectionParsed = document.getElementById('sectionParsed')
const spinner = document.getElementById('spinner')
input.addEventListener('change', (event) => {
const file = event.target.files[0]
if (!file) {
return false
}
sectionParsed.hidden = true
spinner.hidden = false
// Preapare request.
const form = new FormData()
form.append('imageFg', file)
const requestOptions = {
method: 'POST',
body: form,
headers: OPTIONS[MODE].headers
}
// Make request.
fetch(OPTIONS[MODE].url, requestOptions)
.then(response => response.json())
.then(function (response) {
// Parse response and show result image.
const imgBase64 = response.image
console.log(imgBase64)
resultImage.src = 'data:image/png;base64,' + imgBase64
sectionParsed.hidden = false
})
.catch(function (error) {
// Error can be handled here.
console.error(error)
})
.then(function () {
spinner.hidden = true
})
})
})