Please bookmark this page to avoid losing your image tool!

Image Stencil Creator

(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, threshold = 128, invertColorsStr = "false") {
    // 1. Parameter parsing
    // Ensure threshold is a number within a reasonable range (0-255)
    const effectiveThreshold = Math.max(0, Math.min(255, Number(threshold)));

    // Parse invertColorsStr: "true" or "1" means true, otherwise false.
    const invert = String(invertColorsStr).toLowerCase() === "true" || String(invertColorsStr) === "1";

    // 2. Canvas setup
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

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

    // Handle case where image might not be loaded or dimensions are invalid
    if (imgWidth === 0 || imgHeight === 0) {
        console.error("Image has zero width or height. Cannot process. Ensure image is loaded.");
        // Return a minimal canvas to avoid further errors down the line
        canvas.width = 1;
        canvas.height = 1;
        ctx.fillStyle = 'red'; // Indicate error
        ctx.fillRect(0,0,1,1);
        return canvas;
    }

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

    // 3. Draw image to canvas
    // This step is crucial. If originalImg.src is cross-origin and server lacks CORS headers,
    // the canvas becomes "tainted", and getImageData will fail.
    try {
        ctx.drawImage(originalImg, 0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("Error drawing image to canvas (could be due to image loading issues):", e);
        canvas.width = 1; // Minimal canvas
        canvas.height = 1;
        return canvas;
    }


    // 4. Get image data
    let imageData;
    try {
        imageData = ctx.getImageData(0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("Error getting image data. If image is from a different origin, ensure CORS headers are set on the server:", e);
        // Can't process, return the canvas with the original image drawn (if successful) or an empty one
        // For security reasons, can't return the original image data if tainted.
        // A common fallback is to return the canvas as is (with the image drawn) but without pixel manipulation.
        // Or, to indicate failure more clearly:
        const errorCanvas = document.createElement('canvas');
        errorCanvas.width = imgWidth;
        errorCanvas.height = imgHeight;
        const errorCtx = errorCanvas.getContext('2d');
        errorCtx.fillStyle = '#f0f0f0';
        errorCtx.fillRect(0,0,imgWidth, imgHeight);
        errorCtx.fillStyle = 'red';
        errorCtx.textAlign = 'center';
        errorCtx.font = '16px Arial';
        errorCtx.fillText('Error: Could not process image pixels.', imgWidth/2, imgHeight/2);
        return errorCanvas;
    }
    
    const data = imageData.data; // This is a Uint8ClampedArray

    // 5. Process pixels to create stencil effect
    for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i+1];
        const b = data[i+2];
        // Alpha is data[i+3]

        // Calculate grayscale value (Luminance formula)
        const grayscale = 0.299 * r + 0.587 * g + 0.114 * b;

        let stencilColorValue;
        if (grayscale <= effectiveThreshold) {
            // This part of the image is darker than or equal to the threshold
            // In a standard stencil, this becomes black. If inverted, it becomes white.
            stencilColorValue = invert ? 255 : 0;
        } else {
            // This part of the image is lighter than the threshold
            // In a standard stencil, this becomes white. If inverted, it becomes black.
            stencilColorValue = invert ? 0 : 255;
        }

        data[i] = stencilColorValue;     // Red channel
        data[i+1] = stencilColorValue;   // Green channel
        data[i+2] = stencilColorValue;   // Blue channel
        data[i+3] = 255;                 // Alpha channel (fully opaque)
    }

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

    // 7. Return the 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 Stencil Creator is a versatile online tool designed to transform images into stencil-like graphics by processing the original image pixels. Users can set a threshold to determine which parts of the image become black or white, simulating a stencil effect. Additionally, the tool offers an option to invert the colors for creative variations. This tool can be particularly useful for artists, designers, and crafters looking to create templates for painting, printing, or digital artwork, making it ideal for DIY projects, graphic design, and educational purposes.

Leave a Reply

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