Please bookmark this page to avoid losing your image tool!

Image Color 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.
/**
 * Removes a specific color from an image, making pixels of that color transparent.
 *
 * @param {HTMLImageElement} originalImg The original image to process. Must be fully loaded.
 * @param {string} [colorToRemove="lime"] The color to remove. Can be a color name (e.g., "red"),
 *                                        hex code (e.g., "#FF0000", "#F00"), an RGB string 
 *                                        (e.g., "255,0,0" or "rgb(255,0,0)").
 *                                        Defaults to "lime" (pure green: 0,255,0).
 * @param {number} [tolerance=50] The tolerance for color matching. This is the maximum allowed
 *                                sum of absolute differences between the R, G, B channels of
 *                                a pixel's color and the target color. Ranges from 0 (exact match)
 *                                up to 765 (255*3). A higher value means more shades
 *                                of the color will be removed. Defaults to 50.
 * @returns {HTMLCanvasElement} A new canvas element with the specified color removed.
 *                              If errors occur (e.g., image not loaded, cross-origin issues),
 *                              it returns a canvas displaying an error message.
 */
function processImage(originalImg, colorToRemove = "lime", tolerance = 50) {
    // Helper function to parse color string to an RGB object {r, g, b}
    function parseColorToRgb(colorString) {
        const strColor = String(colorString).trim();

        // Try "r,g,b" format first (e.g., "255,0,0")
        const rgbParts = strColor.split(',').map(s => parseInt(s.trim(), 10));
        if (rgbParts.length === 3 && rgbParts.every(p => !isNaN(p) && p >= 0 && p <= 255)) {
            return { r: rgbParts[0], g: rgbParts[1], b: rgbParts[2] };
        }

        // Use a dummy element for other CSS color formats (hex, names, rgb(), rgba())
        const d = document.createElement("div");
        d.style.color = strColor;

        // Element must be in the DOM for getComputedStyle to work reliably.
        let tempElementInDom = false;
        if (document.body) {
            document.body.appendChild(d);
            tempElementInDom = true;
        } else {
            // Fallback if document.body is not available yet (e.g. script in <head> without defer/async)
            // This might lead to less accurate color parsing for complex names if not in DOM.
            console.warn("document.body not available for color parsing. Color parsing might be less accurate for named colors.");
        }
        
        const computedColor = window.getComputedStyle(d).color;
        
        if (tempElementInDom) {
            document.body.removeChild(d);
        }

        // Computed color is usually "rgb(r, g, b)" or "rgba(r, g, b, a)"
        const match = computedColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
        if (match) {
            return { r: parseInt(match[1], 10), g: parseInt(match[2], 10), b: parseInt(match[3], 10) };
        }
        
        console.warn(`Could not parse color: "${strColor}". Defaulting to black (0,0,0).`);
        return { r: 0, g: 0, b: 0 }; // Fallback
    }

    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d', { willReadFrequently: true });

    // Validate the input image object
    if (!(originalImg instanceof HTMLImageElement)) {
        console.error("Invalid input: originalImg is not an HTMLImageElement.");
        canvas.width = 200; canvas.height = 50;
        ctx.fillStyle = "red"; ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.font = "12px Arial"; ctx.fillStyle = "white";  ctx.textAlign = "center";
        ctx.fillText("Error: Input is not an Image.", canvas.width/2, canvas.height/2 + 4);
        return canvas;
    }

    // Validate image dimensions and loaded state
    const imgWidth = originalImg.naturalWidth;
    const imgHeight = originalImg.naturalHeight;

    if (!originalImg.complete || imgWidth === 0 || imgHeight === 0) {
        console.error("Image is not fully loaded or has zero dimensions.");
        canvas.width = 200; canvas.height = 50;
        ctx.fillStyle = "red"; ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.font = "12px Arial"; ctx.fillStyle = "white"; ctx.textAlign = "center";
        let errMsg = "Error: Image not ready.";
        if (!originalImg.complete) errMsg = "Error: Image not complete.";
        else if (imgWidth === 0 || imgHeight === 0) errMsg = "Error: Image has zero dimensions.";
        ctx.fillText(errMsg, canvas.width/2, canvas.height/2 + 4);
        return canvas;
    }

    canvas.width = imgWidth;
    canvas.height = imgHeight;

    try {
        ctx.drawImage(originalImg, 0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("Error drawing image onto canvas:", e);
        canvas.width = 200; canvas.height = 50; // Reset for error message
        ctx.fillStyle = "orange"; ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.font = "12px Arial"; ctx.fillStyle = "black"; ctx.textAlign = "center";
        ctx.fillText("Error: Could not draw image.", canvas.width/2, canvas.height/2 + 4);
        return canvas;
    }

    let imageData;
    try {
        imageData = ctx.getImageData(0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("Error getting ImageData (likely cross-origin issue):", e);
        // For cross-origin issues, the original image IS drawn, so we use that as a base for the message.
        ctx.fillStyle = "rgba(255, 100, 0, 0.75)"; // Semi-transparent orange overlay
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.font = "bold 16px Arial"; 
        ctx.fillStyle = "white"; 
        ctx.textAlign = "center";
        const messageY = canvas.height / 2;
        if (canvas.height > 40) {
             ctx.fillText("Error: Cannot process image pixels.", canvas.width / 2, messageY - 10);
             ctx.fillText("(Likely a cross-origin image)", canvas.width / 2, messageY + 10);
        } else {
             ctx.fillText("Error: Pixel access denied.", canvas.width/2, messageY + 6);
        }
        return canvas; 
    }
    
    const data = imageData.data;
    const targetColor = parseColorToRgb(colorToRemove);
    
    let currentTolerance = typeof tolerance === 'string' ? parseFloat(tolerance) : Number(tolerance);
    if (isNaN(currentTolerance) || currentTolerance < 0) {
        console.warn(`Invalid tolerance value: ${tolerance}. Using 0.`);
        currentTolerance = 0;
    }

    const targetR = targetColor.r;
    const targetG = targetColor.g;
    const targetB = targetColor.b;

    for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];
        // data[i+3] is a_alpha, not used in color matching but modified.

        const diff = Math.abs(r - targetR) + Math.abs(g - targetG) + Math.abs(b - targetB);

        if (diff <= currentTolerance) {
            data[i + 3] = 0; // Set alpha to 0 (fully transparent)
        }
    }

    ctx.putImageData(imageData, 0, 0);
    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 Color Removal Tool allows users to effectively remove a specific color from an image, making it transparent. This tool enables versatility in image editing, where users can select colors to eliminate based on names, hex codes, or RGB values. It is particularly useful for graphic designers and content creators looking to create overlays, remove backgrounds, or isolate specific elements in images. By adjusting the tolerance for color matching, users can control the extent of shades affected by the removal process, making it suitable for both precise edits and broader adjustments.

Leave a Reply

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