Please bookmark this page to avoid losing your image tool!

Image Background Replacement To White

(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.
/**
 * Replaces the background of an image with white based on a color sample from the top-left corner.
 * This function works best with images that have a relatively uniform background color.
 *
 * @param {HTMLImageElement} originalImg The original image object to process.
 * @param {number} tolerance A tolerance value (0-255) to control how similar a color must be to the background color to be replaced. A higher value means more colors will be considered part of the background.
 * @returns {HTMLCanvasElement} A new canvas element with the background replaced by white.
 */
function processImage(originalImg, tolerance = 30) {
    // Create a new canvas element to draw on.
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    // Get the dimensions of the original image.
    const width = originalImg.naturalWidth;
    const height = originalImg.naturalHeight;

    // Set the canvas dimensions to match the image.
    canvas.width = width;
    canvas.height = height;

    // Draw the original image onto the canvas.
    ctx.drawImage(originalImg, 0, 0);

    // Get the image data from the canvas. This might throw a security error
    // if the image is from a different origin (CORS), so we wrap it in a try-catch.
    let imageData;
    try {
        imageData = ctx.getImageData(0, 0, width, height);
    } catch (e) {
        console.error("Could not get image data. This may be due to a cross-origin security issue.", e);
        // In case of an error, return a canvas with an error message.
        ctx.clearRect(0, 0, width, height);
        ctx.fillStyle = '#f0f0f0';
        ctx.fillRect(0, 0, width, height);
        ctx.fillStyle = 'red';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('Error: Cannot process a cross-origin image.', width / 2, height / 2);
        return canvas;
    }


    const data = imageData.data;

    // Pick the color of the top-left pixel (0,0) as the target background color.
    const bgR = data[0];
    const bgG = data[1];
    const bgB = data[2];

    // Define the replacement color (white).
    const replaceR = 255;
    const replaceG = 255;
    const replaceB = 255;
    const replaceA = 255; // Opaque

    // To improve performance, we compare the squared distance to the squared tolerance,
    // avoiding the need for a costly square root calculation in the loop.
    const toleranceSquared = Math.pow(tolerance, 2);

    // Iterate over each pixel of the image. The data is stored in a flat array [R,G,B,A, R,G,B,A, ...].
    for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];

        // Calculate the color difference (squared Euclidean distance in RGB space).
        const distanceSquared = Math.pow(r - bgR, 2) + Math.pow(g - bgG, 2) + Math.pow(b - bgB, 2);

        // If the pixel's color is within the tolerance of the background color, replace it with white.
        if (distanceSquared <= toleranceSquared) {
            data[i] = replaceR;
            data[i + 1] = replaceG;
            data[i + 2] = replaceB;
            data[i + 3] = replaceA;
        }
    }

    // Put the modified pixel data back onto the canvas.
    ctx.putImageData(imageData, 0, 0);

    // Return the resulting canvas.
    return canvas;
}

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 Replacement To White’ tool allows users to automatically replace the background of an image with a solid white color. It analyzes the color of the top-left corner of the image to determine the original background color and uses a tolerance setting to identify which pixels should be replaced. This tool is particularly useful for cleaning up images where the background is relatively uniform, making it ideal for product photos, graphic design, or any situation where a clean white background is desired.

Leave a Reply

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