Please bookmark this page to avoid losing your image tool!

Image Posterization Filter 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, numLevelsParam = "4") {
    // 1. Parameter parsing and validation
    // The numLevelsParam can be a string or number. Default is "4".
    // Convert to string first to handle potential null/undefined if default isn't used, then parse.
    let levels = parseInt(String(numLevelsParam), 10);

    // Clamp levels: must be an integer between 2 and 256.
    // levels = 1 would involve division by zero for the 'factor' calculation (255 / (1-1)) and is not meaningful for posterization.
    // The minimum useful number of levels is 2 (e.g., for a channel, values would map to 0 or 255).
    // The maximum number of levels is 256 (representing all 0-255 values for an 8-bit channel, which implies no change if correctly mapped).
    if (isNaN(levels) || levels < 2) {
        levels = 2; 
    } else if (levels > 256) {
        levels = 256;
    }

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

    // Use naturalWidth/Height if available (actual image dimensions), otherwise fallback to width/height (styled dimensions).
    // This assumes originalImg is a loaded HTMLImageElement or a similar object with these properties.
    const width = originalImg.naturalWidth || originalImg.width;
    const height = originalImg.naturalHeight || originalImg.height;
    canvas.width = width;
    canvas.height = height;

    // 3. Draw image to canvas
    // If the image is not fully loaded or is invalid, drawing might result in an empty/partial canvas.
    // The function relies on a valid, loaded image object for correct operation.
    ctx.drawImage(originalImg, 0, 0, canvas.width, canvas.height);

    // Optimization: if width or height is 0, no processing can be done.
    if (width === 0 || height === 0) {
        return canvas; // Return an empty (0-dimension) canvas
    }

    // 4. Get image data
    // This operation can throw a SecurityError if the image is cross-origin and the
    // appropriate CORS headers are not set, tainting the canvas.
    let imageData;
    try {
        imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    } catch (e) {
        console.error("Error getting image data for posterization filter:", e);
        // Fallback: return the canvas with the original image (already drawn).
        // This meets the requirement of returning a canvas, even if processing failed.
        return canvas;
    }
    const data = imageData.data; // This is a Uint8ClampedArray

    // 5. Apply posterization filter
    // Calculate the factor for quantizing color values.
    // If levels = 256, then levels - 1 = 255. factor = 255 / 255 = 1.
    //   newValue = Math.round(oldValue / 1) * 1 = oldValue. This correctly results in no change to the color values.
    // If levels = 2, then levels - 1 = 1. factor = 255 / 1 = 255.
    //   newValue = Math.round(oldValue / 255) * 255. This maps values to either 0 or 255.
    // Since 'levels' is clamped to be >= 2, (levels - 1) will always be at least 1, preventing division by zero.
    const factor = 255 / (levels - 1);

    for (let i = 0; i < data.length; i += 4) {
        // For each color channel (R, G, B), divide by the factor, round to the nearest integer,
        // then multiply by the factor. This maps the original 0-255 value to one of the 'levels' discrete values.
        data[i]     = Math.round(data[i] / factor) * factor;     // Red channel
        data[i + 1] = Math.round(data[i + 1] / factor) * factor; // Green channel
        data[i + 2] = Math.round(data[i + 2] / factor) * factor; // Blue channel
        // Alpha channel (data[i + 3]) is typically left unchanged in posterization effects.
    }

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

    // 7. 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 Posterization Filter Tool allows users to transform their images by reducing the number of colors used, which creates a stylized effect commonly referred to as posterization. Users can specify the number of color levels for the transformation, enabling creative control over the visual output. This tool is particularly useful for artists, graphic designers, and anyone looking to create unique, visually striking images for digital art, presentations, or social media content. The tool handles various image formats and provides an easy-to-use interface for uploading images and selecting desired posterization settings.

Leave a Reply

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