Please bookmark this page to avoid losing your image tool!

Image Chroma Key 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.
function processImage(originalImg, chromaKeyColor = "0,255,0", tolerance = 50) {
    // 1. Validate originalImg parameter
    // It must be an HTMLImageElement and successfully loaded (non-zero dimensions)
    if (!originalImg || !(originalImg instanceof HTMLImageElement)) {
        console.error("processImage: originalImg parameter must be an HTMLImageElement.");
        const errorCanvas = document.createElement('canvas');
        errorCanvas.width = 1; 
        errorCanvas.height = 1;
        const errorCtx = errorCanvas.getContext('2d');
        if (errorCtx) {
            errorCtx.fillStyle = 'rgba(255,0,0,0.5)'; // Semi-transparent red to indicate error
            errorCtx.fillRect(0,0,1,1);
        }
        return errorCanvas;
    }

    const imgWidth = originalImg.naturalWidth;
    const imgHeight = originalImg.naturalHeight;

    if (imgWidth === 0 || imgHeight === 0) {
        console.warn("processImage: Image has zero dimensions (naturalWidth or naturalHeight is 0). This usually means the image is not loaded yet or is an invalid image. Returning a 1x1 canvas.");
        const emptyCanvas = document.createElement('canvas');
        emptyCanvas.width = 1;
        emptyCanvas.height = 1;
        // Optionally, fill with a color to indicate this state if desired
        // const emptyCtx = emptyCanvas.getContext('2d');
        // if (emptyCtx) { emptyCtx.fillStyle = 'rgba(255,255,0,0.5)'; emptyCtx.fillRect(0,0,1,1); }
        return emptyCanvas; 
    }

    // 2. Setup canvas
    const canvas = document.createElement('canvas');
    canvas.width = imgWidth;
    canvas.height = imgHeight;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) {
        console.error("processImage: Could not get 2D rendering context for the canvas. This might occur in non-browser environments or if canvas is not supported.");
        // Return the canvas, though it's unusable for drawing. The caller might decide what to do.
        return canvas;
    }

    // 3. Draw image to canvas and attempt to get its pixel data
    try {
        ctx.drawImage(originalImg, 0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("processImage: Error drawing the image onto the canvas. The image source might be corrupt, inaccessible, or the image object might be in a broken state.", e);
        // Return the canvas as is; it might be blank or partially drawn.
        return canvas; 
    }

    let imageData;
    try {
        imageData = ctx.getImageData(0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("processImage: Could not get image data from canvas. This often happens due to CORS (Cross-Origin Resource Sharing) policy if the image is loaded from a different origin and the server does not permit cross-origin reading of pixel data. The original image (as drawn on the canvas) is returned without processing.", e);
        // In this case, we can't process pixels, so return the canvas with the original image drawn on it.
        return canvas;
    }
    
    const data = imageData.data; // Pixel data is a Uint8ClampedArray: [R,G,B,A, R,G,B,A, ...]

    // 4. Parse chromaKeyColor parameter (string "R,G,B")
    let targetR = 0, targetG = 255, targetB = 0; // Default to green (0,255,0)
    
    const colorParts = String(chromaKeyColor).split(',');
    if (colorParts.length === 3) {
        const r = parseInt(colorParts[0].trim(), 10);
        const g = parseInt(colorParts[1].trim(), 10);
        const b = parseInt(colorParts[2].trim(), 10);
        
        // Check if parsing was successful and values are valid (0-255)
        if (!isNaN(r) && !isNaN(g) && !isNaN(b) &&
            r >= 0 && r <= 255 && 
            g >= 0 && g <= 255 && 
            b >= 0 && b <= 255) {
            targetR = r;
            targetG = g;
            targetB = b;
        } else {
            // Warn if parsed values are out of range or not numbers
            console.warn(`processImage: Invalid RGB values in chromaKeyColor: "${chromaKeyColor}". Components must be integers between 0 and 255. Using default green (0,255,0).`);
        }
    } else {
        // Warn if the format is incorrect, unless it was the default value that (hypothetically) failed parsing
        if (chromaKeyColor !== "0,255,0") { // Avoid warning if default value itself is passed and somehow misparsed (highly unlikely)
             console.warn(`processImage: Invalid chromaKeyColor format: "${chromaKeyColor}". Expected 'R,G,B' (e.g., '0,255,0'). Using default green (0,255,0).`);
        }
    }

    // 5. Parse and validate tolerance parameter (number)
    let numTolerance = Number(tolerance); // Convert to number type if it was passed as string
    if (isNaN(numTolerance) || numTolerance < 0) {
        console.warn(`processImage: Invalid or negative tolerance value: "${tolerance}". Tolerance must be a non-negative number. Using default tolerance of 50.`);
        numTolerance = 50; // Fallback to default tolerance
    }

    // 6. Iterate through each pixel and apply chroma key effect
    for (let i = 0; i < data.length; i += 4) {
        const rPx = data[i];     // Current pixel's Red component
        const gPx = data[i + 1]; // Current pixel's Green component
        const bPx = data[i + 2]; // Current pixel's Blue component
        // data[i + 3] is the Alpha component, which we will modify if color matches

        // Calculate Euclidean distance in 3D RGB space between the current pixel's color
        // and the target chroma key color.
        const distance = Math.sqrt(
            Math.pow(rPx - targetR, 2) +
            Math.pow(gPx - targetG, 2) +
            Math.pow(bPx - targetB, 2)
        );

        // If the calculated distance is less than the tolerance threshold,
        // this pixel is considered part of the chroma key color.
        // Make this pixel transparent by setting its Alpha component to 0.
        if (distance < numTolerance) {
            data[i + 3] = 0; // Set Alpha to 0 (fully transparent)
        }
    }

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

    // 8. Return the processed 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 Chroma Key Removal Tool allows users to eliminate a specific color from an image, typically used for green screen effects. This tool is particularly useful for video producers and graphic designers who want to replace a background with transparency or another image. By selecting a chroma key color and specifying a tolerance, users can achieve effective removal of unwanted backgrounds, making it ideal for creating professional-looking content in various media projects.

Leave a Reply

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