Please bookmark this page to avoid losing your image tool!

Image Semaphore Flag Filter Effect 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.
async function processImage(originalImg, flagColorsStr = "red,yellow,white,blue,black", blockSize = 10) {
    // 1. Validate parameters
    blockSize = Math.max(1, parseInt(blockSize, 10) || 10); // Ensure blockSize is at least 1

    // 2. Helper function to parse color strings to [r, g, b] array
    // Uses a temporary canvas to convert CSS color strings (like "red", "#FF0000", "rgb(255,0,0)")
    // to their numerical RGB components.
    function parseColorToRGB(colorStr) {
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = 1;
        tempCanvas.height = 1;
        const ctx = tempCanvas.getContext('2d');

        if (!ctx) {
            // This should be extremely rare in modern browsers.
            console.warn(`Could not get 2D context for parsing color: ${colorStr}. Defaulting to black.`);
            return [0, 0, 0]; // Return black as a fallback
        }

        // Set fillStyle. If colorStr is invalid, the browser typically defaults to black
        // or leaves fillStyle unchanged (which is black for a new canvas).
        ctx.fillStyle = colorStr.trim();
        ctx.fillRect(0, 0, 1, 1); // Draw the color onto the 1x1 canvas

        const imageData = ctx.getImageData(0, 0, 1, 1).data;
        return [imageData[0], imageData[1], imageData[2]]; // Return [R, G, B]
    }

    // 3. Parse the flagColorsStr into an array of RGB palette colors
    let palette = flagColorsStr
        .split(',') // Split the string by commas
        .map(color => color.trim()) // Trim whitespace from each color string
        .filter(color => color.length > 0) // Remove any empty strings (e.g., from "red,,blue")
        .map(color => parseColorToRGB(color)); // Convert each color string to an [R, G, B] array

    // If the resulting palette is empty (e.g., input string was empty or all colors were invalid),
    // use a default semaphore-inspired palette.
    if (palette.length === 0) {
        console.warn("Palette is empty or invalid. Using default semaphore colors: red, yellow, white, blue, black.");
        palette = ["red", "yellow", "white", "blue", "black"].map(parseColorToRGB);
    }

    // 4. Create the output canvas
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    if (!ctx) {
        console.error("Could not get 2D context for the main processing canvas.");
        // As per requirements, must return a displayable element.
        // Create a small canvas indicating an error.
        const errorCanvas = document.createElement('canvas');
        errorCanvas.width = originalImg.width > 0 ? originalImg.width : 200;
        errorCanvas.height = originalImg.height > 0 ? originalImg.height : 100;
        const errorCtx = errorCanvas.getContext('2d');
        if (errorCtx) {
            errorCtx.fillStyle = 'lightpink';
            errorCtx.fillRect(0,0,errorCanvas.width, errorCanvas.height);
            errorCtx.fillStyle = 'black';
            errorCtx.font = '16px Arial';
            errorCtx.textAlign = 'center';
            errorCtx.fillText('Error: Canvas not supported.', errorCanvas.width/2, errorCanvas.height/2);
        }
        return errorCanvas;
    }
    
    // Set canvas dimensions from the original image.
    // It's assumed originalImg is a loaded JavaScript Image object,
    // so .width and .height reflect its natural dimensions.
    canvas.width = originalImg.width;
    canvas.height = originalImg.height;

    // If image dimensions are zero, return an empty canvas.
    if (canvas.width === 0 || canvas.height === 0) {
        console.warn("Original image has zero width or height. Returning an empty canvas.");
        return canvas;
    }

    // 5. Draw the original image onto this canvas.
    // The pixel data will be read from and written to this canvas.
    ctx.drawImage(originalImg, 0, 0, canvas.width, canvas.height);

    // 6. Helper function for calculating color distance.
    // Uses squared Euclidean distance for efficiency (square root is not needed for comparison).
    function colorDistanceSquared(rgb1, rgb2) {
        const dr = rgb1[0] - rgb2[0];
        const dg = rgb1[1] - rgb2[1];
        const db = rgb1[2] - rgb2[2];
        return dr * dr + dg * dg + db * db;
    }

    // 7. Helper function to find the closest color in the palette for a given RGB color.
    function findClosestPaletteColor(r, g, b) {
        let minDistance = Infinity;
        // Default to the first color in the palette, or black if palette somehow ended up empty (should not happen).
        let closestColor = palette[0] || [0,0,0]; 

        for (const pColor of palette) {
            const dist = colorDistanceSquared([r, g, b], pColor);
            if (dist < minDistance) {
                minDistance = dist;
                closestColor = pColor;
            }
            if (minDistance === 0) { // Exact match found, no need to check further
                break;
            }
        }
        return closestColor;
    }

    // 8. Process the image in blocks
    // Iterate over the image canvas by blocks of size `blockSize x blockSize`.
    for (let y = 0; y < canvas.height; y += blockSize) {
        for (let x = 0; x < canvas.width; x += blockSize) {
            // Determine the actual width and height of the current block.
            // This is important for blocks at the edges of the image, which might be smaller.
            const currentBlockWidth = Math.min(blockSize, canvas.width - x);
            const currentBlockHeight = Math.min(blockSize, canvas.height - y);

            // Get the pixel data for the current block from the canvas.
            const imageData = ctx.getImageData(x, y, currentBlockWidth, currentBlockHeight);
            const data = imageData.data; // data is a Uint8ClampedArray: [R,G,B,A, R,G,B,A, ...]
            
            let sumR = 0, sumG = 0, sumB = 0;
            const numPixelsInBlock = currentBlockWidth * currentBlockHeight;

            if (numPixelsInBlock === 0) continue; // Skip if block is somehow empty

            // Calculate the average color of all pixels in the block.
            for (let i = 0; i < data.length; i += 4) {
                sumR += data[i];   // Red component
                sumG += data[i+1]; // Green component
                sumB += data[i+2]; // Blue component
                // Alpha component (data[i+3]) is ignored for average color calculation.
            }

            const avgR = sumR / numPixelsInBlock;
            const avgG = sumG / numPixelsInBlock;
            const avgB = sumB / numPixelsInBlock;

            // Find the color in the defined palette that is closest to this average color.
            const [paletteR, paletteG, paletteB] = findClosestPaletteColor(avgR, avgG, avgB);

            // Fill the entire block on the canvas with this closest palette color.
            ctx.fillStyle = `rgb(${paletteR},${paletteG},${paletteB})`;
            ctx.fillRect(x, y, currentBlockWidth, currentBlockHeight);
        }
    }

    // 9. Return the modified 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 Semaphore Flag Filter Effect Tool allows users to apply a distinct artistic effect to images by processing them through a block-based color averaging technique. This tool uses a customizable palette inspired by semaphore signal flag colors, which can include options like red, yellow, white, blue, and black. Users can specify the colors in the palette and the block size for processing. Applications include creating unique visual styles for digital art, providing a pop-art effect for photographs, simplifying images for graphic design projects, or enhancing images for presentations and social media. The output is a transformed image that maintains the essence of the original while introducing a colorful abstraction.

Leave a Reply

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