Please bookmark this page to avoid losing your image tool!

Image Selective Colorization Background Remover

(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.
function processImage(originalImg, colorsToKeep = "#ff0000", tolerance = 80) {
    /**
     * Helper function to convert a hex color string to an RGB object.
     * Handles 3-digit and 6-digit hex codes, with or without a leading '#'.
     * Returns null for invalid input.
     * @param {string} hex - The hex color string (e.g., "#ff0000").
     * @returns {{r: number, g: number, b: number} | null} - The RGB object or null.
     */
    const hexToRgb = (hex) => {
        if (!hex || typeof hex !== 'string') {
            return null;
        }

        // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
        let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, (m, r, g, b) => {
            return r + r + g + g + b + b;
        });

        let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    };

    // Create a canvas element to work with
    const canvas = document.createElement('canvas');
    // Using { willReadFrequently: true } is a performance hint for browsers when using getImageData frequently
    const ctx = canvas.getContext('2d', {
        willReadFrequently: true
    });

    // Set canvas dimensions to match the image
    // Using naturalWidth/Height is more reliable for fully loaded images
    canvas.width = originalImg.naturalWidth || originalImg.width;
    canvas.height = originalImg.naturalHeight || originalImg.height;

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

    // Parse the comma-separated string of colors to keep and convert them to RGB objects
    const targetRgbColors = colorsToKeep
        .split(',')
        .map(color => hexToRgb(color.trim()))
        .filter(rgb => rgb !== null); // Filter out any invalid color strings

    // Get the pixel data from the canvas
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imageData.data;

    // Use squared tolerance to avoid expensive square root calculations inside the loop
    const toleranceSquared = Math.pow(tolerance, 2);

    // Iterate over each pixel in the image data array
    // Each pixel is represented by 4 consecutive values: 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];

        let keepColor = false;

        // If no valid target colors are specified, the entire image will become grayscale.
        // Otherwise, check if the current pixel's color is within the tolerance of any target color.
        if (targetRgbColors.length > 0) {
            for (const targetColor of targetRgbColors) {
                // Calculate the squared Euclidean distance in the RGB color space.
                // This measures how "far" the pixel's color is from the target color.
                const distanceSq = Math.pow(r - targetColor.r, 2) +
                    Math.pow(g - targetColor.g, 2) +
                    Math.pow(b - targetColor.b, 2);

                if (distanceSq <= toleranceSquared) {
                    keepColor = true;
                    break; // A match is found, no need to check other target colors for this pixel.
                }
            }
        }

        // If the color is not within the tolerance of any target color, convert it to grayscale.
        if (!keepColor) {
            // Use the luminosity method for a perceptually accurate grayscale conversion.
            const gray = (0.299 * r) + (0.587 * g) + (0.114 * b);
            data[i] = gray; // Red
            data[i + 1] = gray; // Green
            data[i + 2] = gray; // Blue
        }
        // The alpha channel (data[i + 3]) is left unchanged to preserve transparency.
    }

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

    // Return the final canvas element, which now displays the selectively colorized image.
    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 Selective Colorization Background Remover is a tool that allows users to selectively keep specific colors in an image while converting the rest of the image to grayscale. By specifying hex color codes, users can highlight desired hues, such as red or blue, and achieve creative effects ideal for enhancing photo presentations or artistic projects. This tool is useful for graphic designers, photographers, and anyone looking to emphasize certain colors in their images while creating a striking visual contrast.

Leave a Reply

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