Please bookmark this page to avoid losing your image tool!

Image Binary Lua Table Shrinker

(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 a "shrunk" binary representation as a Lua table.
 * The shrinking is achieved by converting the image to 1-bit color (binary)
 * and then packing the bits of each row into bytes.
 * The output is a string of Lua code inside a <pre> element, which includes
 * the packed image data and a helper function to decode it.
 *
 * @param {Image} originalImg The original Image object to process.
 * @param {number} threshold The brightness threshold (0-255) to determine if a pixel is black or white.
 *                           Pixels with luminance below this value become black (1), others white (0).
 *                           Defaults to 128.
 * @returns {HTMLElement} A <pre> element containing the Lua code.
 */
async function processImage(originalImg, threshold = 128) {
    // Sanitize the threshold parameter
    let safeThreshold = Number(threshold);
    if (isNaN(safeThreshold)) {
        safeThreshold = 128;
    }
    safeThreshold = Math.max(0, Math.min(255, safeThreshold));

    // Create a canvas to read pixel data from the image
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const width = originalImg.naturalWidth;
    const height = originalImg.naturalHeight;
    canvas.width = width;
    canvas.height = height;

    // Draw the image onto the canvas
    ctx.drawImage(originalImg, 0, 0);
    const imageData = ctx.getImageData(0, 0, width, height);
    const data = imageData.data;

    // Begin constructing the Lua table string
    let luaString = `local image_data = {\n`;
    luaString += `  width = ${width},\n`;
    luaString += `  height = ${height},\n`;
    luaString += `  data = {\n`;

    // Process each row of the image
    for (let y = 0; y < height; y++) {
        const rowBits = [];
        for (let x = 0; x < width; x++) {
            const index = (y * width + x) * 4;
            const r = data[index];
            const g = data[index + 1];
            const b = data[index + 2];
            const a = data[index + 3];

            let bit = 0; // Default to white (0) for transparent or light pixels
            
            // Consider non-transparent pixels only
            if (a > 128) {
                // Use the standard luminance formula for better grayscale conversion
                const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
                if (luminance < safeThreshold) {
                    bit = 1; // Black (1) for dark pixels
                }
            }
            rowBits.push(bit);
        }

        // Pack the collected bits for the row into bytes (numbers from 0-255)
        const packedRow = [];
        for (let i = 0; i < rowBits.length; i += 8) {
            const chunk = rowBits.slice(i, i + 8);
            
            // Pad the last chunk if it's not a full byte
            while (chunk.length < 8) {
                chunk.push(0);
            }
            
            const byteString = chunk.join('');
            const byteValue = parseInt(byteString, 2);
            packedRow.push(byteValue);
        }

        // Format the row as a Lua table entry
        luaString += `    {${packedRow.join(', ')}},\n`;
    }

    // Close the Lua table structures
    luaString += `  }\n`;
    luaString += `}\n\n`;

    // Append a helper function in Lua to decode the data, making the output immediately usable
    luaString += `-- Helper function to decode the image data back into a 2D pixel map (1s and 0s).\n`;
    luaString += `-- Works in Lua versions without native bitwise operators.\n`;
    luaString += `function decode_image(img_data)\n`;
    luaString += `  local decoded = {}\n`;
    luaString += `  for y = 1, img_data.height do\n`;
    luaString += `    decoded[y] = {}\n`;
    luaString += `    local bit_index = 1\n`;
    luaString += `    for _, byte in ipairs(img_data.data[y]) do\n`;
    luaString += `      for j = 7, 0, -1 do\n`;
    luaString += `        if bit_index <= img_data.width then\n`;
    luaString += `          local mask = 2^j\n`;
    luaString += `          if byte >= mask then\n`;
    luaString += `            decoded[y][bit_index] = 1\n`;
    luaString += `            byte = byte - mask\n`;
    luaString += `          else\n`;
    luaString += `            decoded[y][bit_index] = 0\n`;
    luaString += `          end\n`;
    luaString += `          bit_index = bit_index + 1\n`;
    luaString += `        end\n`;
    luaString += `      end\n`;
    luaString += `    end\n`;
    luaString += `  end\n`;
    luaString += `  return decoded\n`;
    luaString += `end\n\n`;
    luaString += `-- Example usage:\n`;
    luaString += `-- local pixel_map = decode_image(image_data)\n`;
    luaString += `-- local pixel_value = pixel_map[1][1] -- Get the top-left pixel\n`;


    // Create a <pre> element to display the code nicely
    const pre = document.createElement('pre');
    const code = document.createElement('code');
    code.textContent = luaString;
    pre.appendChild(code);
    
    // Apply some styling for better readability
    pre.style.backgroundColor = '#f4f4f4';
    pre.style.border = '1px solid #ddd';
    pre.style.borderRadius = '5px';
    pre.style.padding = '15px';
    pre.style.margin = '0';
    pre.style.whiteSpace = 'pre-wrap';
    pre.style.wordBreak = 'break-all';
    pre.style.textAlign = 'left';
    code.style.fontFamily = 'monospace';
    code.style.fontSize = '14px';

    return pre;
}

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 Binary Lua Table Shrinker is an online tool that converts images into a compact binary representation within a Lua table format. By applying a brightness threshold, it transforms the image into a 1-bit color format, categorizing pixels as either black or white based on their luminance. This process not only shrinks the image data for efficient storage but also provides a Lua code snippet that includes a helper function for decoding the binary data back into a usable 2D pixel map. Use cases for this tool include game development, where developers may need to optimize image assets, or for educational purposes in programming and image processing in Lua.

Leave a Reply

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