Please bookmark this page to avoid losing your image tool!

Image Table Action 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.
/**
 * Converts an image into an HTML table representation, where each cell's
 * background color corresponds to the average color of a block of pixels
 * in the original image. This creates a "pixelated" or mosaic effect using table cells.
 *
 * @param {HTMLImageElement} originalImg The original image object. The image must be fully loaded.
 * @param {number} [blockSize=8] The side length of the square pixel block from the original
 *   image to be represented by a single table cell. A smaller value creates a more
 *   detailed but computationally heavier table, while a larger value creates a more
 *   abstract and faster-to-render table.
 * @returns {HTMLElement} An HTML table element that visually represents the image, or a div with an error message.
 */
function processImage(originalImg, blockSize = 8) {
    // 1. Sanitize the blockSize parameter
    const safeBlockSize = Math.max(1, Math.floor(blockSize));

    // 2. Use a canvas to read the image's pixel data
    const canvas = document.createElement('canvas');
    // Add willReadFrequently hint for potential performance optimization by the browser
    const ctx = canvas.getContext('2d', {
        willReadFrequently: true
    });

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

    if (imgWidth === 0 || imgHeight === 0) {
        const errorDiv = document.createElement('div');
        errorDiv.textContent = 'Error: The provided image has zero width or height.';
        return errorDiv;
    }

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

    // Draw the image onto the canvas to access its data
    ctx.drawImage(originalImg, 0, 0);

    // 3. Get all pixel data at once for performance
    let imageData;
    try {
        // This operation can fail due to cross-origin security restrictions
        imageData = ctx.getImageData(0, 0, imgWidth, imgHeight);
    } catch (e) {
        console.error("Could not get image data. This may be due to a Cross-Origin (CORS) issue.", e);
        const errorDiv = document.createElement('div');
        errorDiv.textContent = 'Error: Could not process the image, possibly due to a cross-origin security policy. Try using an image from the same domain.';
        errorDiv.style.color = 'red';
        errorDiv.style.padding = '10px';
        errorDiv.style.border = '1px solid red';
        errorDiv.style.fontFamily = 'monospace';
        return errorDiv;
    }
    const data = imageData.data;

    // 4. Create the table element and set base styles
    const table = document.createElement('table');
    const tbody = document.createElement('tbody');
    table.appendChild(tbody);
    table.style.borderCollapse = 'collapse';
    table.style.margin = '0 auto'; // Center the table

    // 5. Iterate through the image by blocks
    for (let y = 0; y < imgHeight; y += safeBlockSize) {
        const tr = document.createElement('tr');

        for (let x = 0; x < imgWidth; x += safeBlockSize) {
            // --- Calculate the average color of the current block ---
            let totalR = 0,
                totalG = 0,
                totalB = 0,
                totalA = 0;
            let pixelCount = 0;

            // Define the block's boundaries, clamping to the image edges
            const blockYEnd = Math.min(y + safeBlockSize, imgHeight);
            const blockXEnd = Math.min(x + safeBlockSize, imgWidth);

            // Loop through each pixel within the block
            for (let by = y; by < blockYEnd; by++) {
                for (let bx = x; bx < blockXEnd; bx++) {
                    const index = (by * imgWidth + bx) * 4;
                    totalR += data[index];
                    totalG += data[index + 1];
                    totalB += data[index + 2];
                    totalA += data[index + 3];
                    pixelCount++;
                }
            }

            // Compute the average RGBA values
            const avgR = Math.floor(totalR / pixelCount);
            const avgG = Math.floor(totalG / pixelCount);
            const avgB = Math.floor(totalB / pixelCount);
            const avgA = (totalA / pixelCount) / 255;

            // 6. Create and style the table cell (td)
            const td = document.createElement('td');
            td.style.padding = '0';
            td.style.backgroundColor = `rgba(${avgR}, ${avgG}, ${avgB}, ${avgA})`;

            // Set the cell size to match the block size, handling edge cases
            const cellWidth = blockXEnd - x;
            const cellHeight = blockYEnd - y;
            td.style.width = `${cellWidth}px`;
            td.style.height = `${cellHeight}px`;

            // Prevent default text styles from affecting small cell dimensions
            td.style.fontSize = '0';

            tr.appendChild(td);
        }
        tbody.appendChild(tr);
    }

    // 7. Return the completed table element
    return table;
}

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 Table Action Tool converts an image into a visually appealing HTML table representation, where each cell’s background color reflects the average color of a corresponding block of pixels from the original image. This tool is useful for creating pixelated or mosaic effects for images, which can be applied in web design, digital art, and social media content. Users can adjust the detail of the representation by specifying the block size, allowing for both abstract and detailed visual outcomes.

Leave a Reply

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