Advanced Background Remover Tool
Advanced Background Remover
Upload your image and instantly remove the background with AI-powered technology. Works perfectly for product photos, portraits, and more.
// Replace the existing processImage() function with this more robust version
async function processImage() {
if (!uploadedFile) return;
try {
loadingIndicator.classList.add('active');
processBtn.disabled = true;
errorMessage.style.display = 'none';
// Additional validation
if (uploadedFile.size > 8 * 1024 * 1024) {
throw new Error('Image size exceeds 8MB limit');
}
if (!['image/jpeg', 'image/png', 'image/webp'].includes(uploadedFile.type)) {
throw new Error('Unsupported image format. Please use JPEG or PNG');
}
// Load rembg library dynamically with fallback
if (typeof rembg === 'undefined') {
await loadRembgLibrary();
}
const imageData = await readFileAsArrayBuffer(uploadedFile);
const imageBytes = new Uint8Array(imageData);
const edgePrecision = parseInt(edgeSlider.value) / 100;
// Add timeout to prevent hanging
const processingTimeout = setTimeout(() => {
throw new Error('Processing took too long. Try a smaller image.');
}, 30000); // 30 seconds timeout
const resultBytes = await rembg.remove(imageBytes, {
model: 'u2net',
alphaMatting: true,
alphaMattingErodeSize: Math.round(10 * edgePrecision)
});
clearTimeout(processingTimeout);
resultBlob = new Blob([resultBytes], { type: 'image/png' });
resultImage.src = URL.createObjectURL(resultBlob);
resultsContainer.style.display = 'flex';
} catch (error) {
console.error('Processing error:', error);
showError(error.message || 'An error occurred while processing the image. Please try again.');
} finally {
loadingIndicator.classList.remove('active');
processBtn.disabled = false;
}
}
// Add this new function to load the library
async function loadRembgLibrary() {
try {
// Try loading from CDN first
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/@imgly/background-removal@1.0.0/dist/bundle.js';
script.integrity = 'sha384-xyz123'; // Add proper integrity hash
script.crossOrigin = 'anonymous';
document.body.appendChild(script);
await new Promise((resolve, reject) => {
script.onload = resolve;
script.onerror = () => reject(new Error('Failed to load background removal library'));
});
return true;
} catch (error) {
console.error('Failed to load rembg:', error);
throw new Error('Background removal service is currently unavailable. Please try again later.');
}
}
function showError(message, duration = 5000) {
errorMessage.innerHTML = `
${message}
`;
errorMessage.style.display = 'flex';
if (duration > 0) {
setTimeout(() => {
errorMessage.style.display = 'none';
}, duration);
}
}
// Add this at the beginning of handleFileUpload
if (file.size > 8 * 1024 * 1024) {
showError('File size exceeds 8MB limit. Please use a smaller image.');
return;
}
// Add this to your CSS
.preview-image {
max-width: 100%;
max-height: 200px;
margin-top: 1rem;
border-radius: 8px;
display: none;
}
// Add this to your upload area HTML (after the upload-subtext div)
![Preview]()
// Add this to handleFileUpload after reader.onload
const imagePreview = document.getElementById('imagePreview');
imagePreview.src = e.target.result;
imagePreview.style.display = 'block';
// Check for WebAssembly support (required by rembg)
if (!('WebAssembly' in window)) {
showError('Your browser doesn\'t support WebAssembly. Please use Chrome, Firefox, or Edge.', 0);
document.getElementById('uploadArea').style.pointerEvents = 'none';
document.getElementById('processBtn').disabled = true;
}
Comments
Post a Comment