Please bookmark this page to avoid losing your image tool!

Image Hexadecimal Color Code Extractor

(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, numColors = 8, quality = 10) {
    // 1. Parameter sanitization
    const numColorsValidated = Math.max(1, Number(numColors) || 8);
    const qualityValidated = Math.max(1, Number(quality) || 10);

    // 2. Canvas setup to read pixel data
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d', {
        willReadFrequently: true
    });
    if (!ctx) {
        const errorDiv = document.createElement('div');
        errorDiv.textContent = 'Could not get canvas context.';
        return errorDiv;
    }

    // 3. Scale down large images for better performance
    const MAX_DIMENSION = 500;
    let {
        width,
        height
    } = originalImg;
    if (width > MAX_DIMENSION || height > MAX_DIMENSION) {
        const ratio = Math.min(MAX_DIMENSION / width, MAX_DIMENSION / height);
        width = Math.round(width * ratio);
        height = Math.round(height * ratio);
    }
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(originalImg, 0, 0, width, height);

    // 4. Get image data and count color occurrences
    let imageData;
    try {
        imageData = ctx.getImageData(0, 0, width, height);
    } catch (e) {
        console.error(e);
        const errorDiv = document.createElement('div');
        errorDiv.textContent = 'Could not process image. It may be from a different origin (CORS issue).';
        errorDiv.style.color = 'red';
        errorDiv.style.padding = '20px';
        return errorDiv;
    }

    const data = imageData.data;
    const colorCounts = {};
    // Iterate over pixels with a step determined by quality. A smaller step means better
    // quality but slower processing. `4` is for the 4 RGBA components.
    const step = 4 * qualityValidated;

    for (let i = 0; i < data.length; i += step) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];
        const a = data[i + 3];

        // Ignore mostly transparent pixels
        if (a < 128) {
            continue;
        }

        // Convert RGB to a hex string
        const hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();

        colorCounts[hex] = (colorCounts[hex] || 0) + 1;
    }

    // 5. Sort colors by frequency and take the top N
    const sortedColors = Object.entries(colorCounts)
        .sort(([, countA], [, countB]) => countB - countA)
        .slice(0, numColorsValidated);

    // 6. Create the output HTML element
    const container = document.createElement('div');
    container.style.display = 'flex';
    container.style.flexWrap = 'wrap';
    container.style.gap = '15px';
    container.style.padding = '10px';
    container.style.justifyContent = 'center';
    container.style.fontFamily = 'monospace, "Courier New", Courier';

    if (sortedColors.length === 0) {
        container.textContent = 'No significant colors found. The image might be empty or fully transparent.';
        return container;
    }

    // 7. Generate a color card for each of the top colors
    sortedColors.forEach(([hex]) => {
        const color = `#${hex}`;

        const card = document.createElement('div');
        card.style.border = '1px solid #ddd';
        card.style.borderRadius = '8px';
        card.style.overflow = 'hidden';
        card.style.width = '130px';
        card.style.textAlign = 'center';
        card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';

        const swatch = document.createElement('div');
        swatch.style.width = '100%';
        swatch.style.height = '90px';
        swatch.style.backgroundColor = color;
        swatch.style.borderBottom = '1px solid #ddd';

        const info = document.createElement('div');
        info.style.padding = '10px';
        info.style.backgroundColor = '#f9f9f9';

        const hexCode = document.createElement('div');
        hexCode.textContent = color;
        hexCode.style.fontWeight = 'bold';
        hexCode.style.cursor = 'pointer';
        hexCode.title = 'Click to copy';

        // Add click-to-copy functionality
        hexCode.onclick = () => {
            navigator.clipboard.writeText(color).then(() => {
                const originalText = hexCode.textContent;
                hexCode.textContent = 'Copied!';
                hexCode.style.color = '#007bff';
                setTimeout(() => {
                    hexCode.textContent = originalText;
                    hexCode.style.color = 'inherit';
                }, 1200);
            }).catch(err => {
                console.error('Failed to copy color to clipboard: ', err);
                alert('Could not copy color.');
            });
        };

        info.appendChild(hexCode);
        card.appendChild(swatch);
        card.appendChild(info);
        container.appendChild(card);
    });

    return container;
}

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 Hexadecimal Color Code Extractor is a tool that allows users to extract the most prominent colors from an image and present them in hexadecimal format. This tool is particularly useful for designers, artists, and developers who need to analyze the color palette of an image for various applications, such as graphic design, web development, or color matching. Users can specify the number of colors to extract and the processing quality, resulting in a visually appealing display of color swatches along with their corresponding hex codes, which can easily be copied to the clipboard.

Leave a Reply

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