Please bookmark this page to avoid losing your image tool!

Image Color Replacement 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, colorToReplaceStr = "255,0,0", replacementColorStr = "0,0,255", tolerance = 30) {

    // Helper function to parse color strings like "R,G,B" or "R,G,B,A"
    // Returns an object {r, g, b, a} or null if parsing fails.
    function parseColor(colorString, colorNameForErrorLog) {
        if (typeof colorString !== 'string') {
            console.error(`Invalid ${colorNameForErrorLog}: expected a string, got ${typeof colorString}.`);
            return null;
        }

        const parts = colorString.split(',').map(s => parseInt(s.trim(), 10));
        
        if (parts.length < 3 || parts.length > 4) {
            console.error(`Invalid ${colorNameForErrorLog} string: "${colorString}". Expected 3 (R,G,B) or 4 (R,G,B,A) components.`);
            return null;
        }

        const r = parts[0];
        const g = parts[1];
        const b = parts[2];
        const a = parts.length === 4 ? parts[3] : 255; // Default alpha to 255 if not provided

        if ([r, g, b, a].some(isNaN)) {
            console.error(`Invalid ${colorNameForErrorLog} string: "${colorString}". Components must be numbers.`);
            return null;
        }

        if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255 || a < 0 || a > 255) {
            console.error(`Invalid ${colorNameForErrorLog} string: "${colorString}". Components must be between 0 and 255.`);
            return null;
        }
        
        return { r, g, b, a };
    }

    const canvas = document.createElement('canvas');
    // Use naturalWidth/Height for intrinsic image dimensions
    const imgWidth = originalImg.naturalWidth || originalImg.width;
    const imgHeight = originalImg.naturalHeight || originalImg.height;
    
    canvas.width = imgWidth;
    canvas.height = imgHeight;
    
    const ctx = canvas.getContext('2d', { willReadFrequently: true });

    if (!ctx) {
        console.error("Could not get 2D context from canvas.");
        // Return an empty canvas of the correct size if context cannot be obtained
        return canvas;
    }

    // Draw the original image onto the canvas first. This handles various image types.
    try {
        ctx.drawImage(originalImg, 0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("Error drawing image onto canvas.", e);
        // Return canvas, which might be empty or partially drawn
        return canvas;
    }
    
    // If image dimensions are zero (e.g., image not loaded or invalid), no processing can be done.
    if (imgWidth === 0 || imgHeight === 0) {
        console.warn("Image has zero width or height. Returning canvas with original (potentially empty) draw.");
        return canvas;
    }
    
    const targetColor = parseColor(colorToReplaceStr, "colorToReplace");
    const newColor = parseColor(replacementColorStr, "replacementColor");
    
    // Ensure tolerance is a non-negative number.
    const effectiveTolerance = Math.max(0, Number(tolerance)); 
    if (isNaN(effectiveTolerance)) {
        console.error(`Invalid tolerance value: ${tolerance}. Using 0.`);
        tolerance = 0; // Fallback to 0 if Number(tolerance) is NaN
    }


    // If color parsing failed, or other critical setup issue, return the canvas with the original image.
    if (!targetColor || !newColor) {
        console.error("Aborting color replacement due to invalid color string(s) or other issues. Original image is returned on canvas.");
        return canvas; // Canvas already contains the original image
    }

    let imageData;
    try {
        imageData = ctx.getImageData(0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("Could not get image data. This might be due to CORS issues if the image is from another domain and the canvas is tainted. Original image is returned on canvas.", e);
        // Return canvas with the original image drawn, as processing is not possible
        return canvas;
    }
    
    const data = imageData.data; // This is a Uint8ClampedArray: [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];
        // const currentAlpha = data[i+3]; // Original alpha of the pixel, not used in matching here

        // Calculate color difference using Manhattan distance in RGB space.
        // Alpha component of the targetColor is not considered for matching by default.
        const diff = Math.abs(r - targetColor.r) +
                     Math.abs(g - targetColor.g) +
                     Math.abs(b - targetColor.b);
        
        // If the current pixel's color is within the tolerance of the target color
        if (diff <= effectiveTolerance) {
            // Replace the pixel's color with the newColor (including its alpha component)
            data[i]   = newColor.r;
            data[i+1] = newColor.g;
            data[i+2] = newColor.b;
            data[i+3] = newColor.a; 
        }
    }

    // Put the modified pixel data back onto the canvas
    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 Replacement Tool allows users to modify images by replacing a specified color with a new one. Users can select the color they wish to replace, provide a replacement color, and set a tolerance level for the color matching. This tool can be beneficial for graphic designers looking to change color schemes in images, for artists wanting to experiment with different color palettes, or for anyone needing to adapt images to fit specific design needs. The intuitive interface ensures a straightforward experience for transforming images efficiently.

Leave a Reply

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