Please bookmark this page to avoid losing your image tool!

Image Background Removal Tool

(Free & Supports Bulk Upload)

Drag & drop your images here or

The result will appear here...
You can edit the below JavaScript code to customize the image tool.
async function processImage(originalImg) {

    // Helper function to ensure the HTMLImageElement is loaded and valid
    const ensureImageLoaded = (imageElement) => {
        return new Promise((resolve, reject) => {
            // Assumes imageElement is already validated as HTMLImageElement by the caller

            if (imageElement.complete) { // Image loading process is complete
                if (imageElement.naturalWidth !== 0 && imageElement.naturalHeight !== 0) {
                    resolve(); // Loaded successfully and has dimensions
                } else {
                    // Complete but 0x0 dimensions, implies error or invalid image
                    let errorMsg = "Image loading completed, but the image is broken or has zero dimensions.";
                    if (imageElement.src) errorMsg += ` Src: ${imageElement.src}`;
                    reject(new Error(errorMsg));
                }
            } else {
                // Image is not yet loaded
                // Check if src or srcset is missing, which would prevent loading
                if (!imageElement.src && !imageElement.srcset) {
                    reject(new Error("HTMLImageElement has no src or srcset attribute. Cannot load."));
                    return;
                }
                
                const onLoadCallback = () => {
                    cleanupEventListeners();
                    if (imageElement.naturalWidth !== 0 && imageElement.naturalHeight !== 0) {
                        resolve();
                    } else {
                        // Loaded but resolved to a 0x0 image.
                        let errorMsg = "Image loaded, but has zero dimensions (naturalWidth/Height is 0).";
                        if (imageElement.src) errorMsg += ` Src: ${imageElement.src}`;
                        reject(new Error(errorMsg));
                    }
                };

                const onErrorCallback = (errorEvent) => {
                    cleanupEventListeners();
                    let errorMsg = "Failed to load image.";
                    if (imageElement.src) errorMsg += ` Src: ${imageElement.src}`;
                    // console.error("Image loading error event:", errorEvent); // For debugging an actual errorEvent object is useful
                    reject(new Error(errorMsg));
                };

                const cleanupEventListeners = () => {
                    imageElement.removeEventListener('load', onLoadCallback);
                    imageElement.removeEventListener('error', onErrorCallback);
                };

                imageElement.addEventListener('load', onLoadCallback);
                imageElement.addEventListener('error', onErrorCallback);
            }
        });
    };

    // Validate input originalImg type. Prompt specifies "javascript Image object", meaning HTMLImageElement.
    if (!(originalImg instanceof HTMLImageElement)) {
        throw new Error("Parameter 'originalImg' must be an HTMLImageElement (an Image object).");
    }

    try {
        // 1. Ensure the original image is loaded and valid
        await ensureImageLoaded(originalImg);

        // 2. Dynamically import the background removal library
        // Using a specific version for stability. Check npm for the latest stable version if needed.
        const version = "1.5.0"; 
        const { removeBackground } = await import(`https://cdn.jsdelivr.net/npm/@imgly/background-removal@${version}/dist/browser.mjs`);

        // 3. Configuration for the library (optional)
        // By default, assets (WASM, model files) are fetched from:
        // `https://cdn.jsdelivr.net/npm/@imgly/background-removal@${version}/dist/assets/`
        const config = {
            // publicPath: `https://cdn.jsdelivr.net/npm/@imgly/background-removal@${version}/dist/assets/`, // Explicitly set if needed
            // progress: (key, current, total) => { // Optional: for download/processing progress
            //   console.log(`imgly-background-removal (${key}): ${current} / ${total}`);
            // },
            // debug: true // Optional: for verbose logging from the library
        };

        // 4. Remove the background. Input is HTMLImageElement. Output is a Blob.
        const blob = await removeBackground(originalImg, config);

        // 5. Create a new HTMLImageElement from the resulting Blob
        const imageURL = URL.createObjectURL(blob);
        const resultImage = new Image();

        // Load the result image (which is now background-free)
        // Using a self-cleaning promise for loading
        await new Promise((resolve, reject) => {
            const cleanup = () => {
                resultImage.onload = null;
                resultImage.onerror = null;
                URL.revokeObjectURL(imageURL); // Important: Clean up the object URL after use
            };
            resultImage.onload = () => {
                cleanup();
                resolve();
            };
            resultImage.onerror = (err) => {
                cleanup();
                console.error("Failed to load the background-removed image from blob URL.", err);
                reject(new Error('Failed to load the processed image with background removed.'));
            };
            resultImage.src = imageURL;
        });
        
        // 6. Create a canvas and draw the result image onto it
        const canvas = document.createElement('canvas');
        canvas.width = resultImage.naturalWidth;
        canvas.height = resultImage.naturalHeight;

        // Ensure the canvas has valid dimensions (e.g., image wasn't empty)
        if (canvas.width === 0 || canvas.height === 0) {
            throw new Error("Resulting image after background removal has zero dimensions. Processing might have failed or produced an empty image.");
        }

        const ctx = canvas.getContext('2d');
        ctx.drawImage(resultImage, 0, 0, canvas.width, canvas.height);

        // 7. Return the canvas
        return canvas;

    } catch (error) {
        // Log the error and re-throw it for the caller to handle appropriately.
        console.error("Error during image background removal process:", error);
        throw error;
    }
}

Free Image Tool Creator

Can't find the image tool you're looking for?
Create one based on your own needs now!

Description

The Image Background Removal Tool is designed to help users effortlessly remove the background from images. This tool is particularly useful for graphic designers, photographers, and content creators who want to isolate subjects or create transparent backgrounds for images used in web design, presentations, or marketing materials. By simply uploading an image, users can obtain a cleaned-up version with the background removed, allowing for seamless integration into various projects or further editing.

Leave a Reply

Your email address will not be published. Required fields are marked *