In JavaScript, get an image’s average color by drawing it on a canvas, reading its RGBA pixels with getImageData(), and calculating an alpha-weighted arithmetic mean of the red, green, and blue channels.

This produces one representative HEX and RGB value, not necessarily a color that occurs in the source. It suits a rough background match, placeholder style, thumbnail summary, design inventory entry, or quick visual comparison; it does not extract a palette of dominant colors.

js get image average color
JS Get Image Average Color: Alpha-Weighted Code

Calculate an image average color in JavaScript

Canvas provides the browser pixel interface for this task: getImageData() returns 8-bit RGBA data, as described in MDN’s CanvasRenderingContext2D.getImageData reference and defined by the WHATWG canvas pixel-manipulation specification.

  1. Finish decoding the image. Wait for image.decode() or the load event, then confirm that naturalWidth and naturalHeight are greater than zero.
  2. Create a canvas at the image’s natural dimensions. Draw the image onto the canvas with drawImage().
  3. Read the complete RGBA pixel array. Call getImageData() over the canvas area and inspect each four-byte pixel group.
  4. Accumulate alpha-weighted channels. Skip pixels with zero alpha, multiply each visible pixel’s red, green, and blue channel by its alpha, and add those values to separate channel totals.
  5. Round and format the output. Divide each channel total by total alpha, round to the nearest integer, and convert the three channels into a six-digit HEX color.

Complete full-resolution JavaScript function:

function getAverageColor(image) { const width = image.naturalWidth; const height = image.naturalHeight; if (width === 0 || height === 0) throw new Error("Image has no valid dimensions."); const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; const context = canvas.getContext("2d", { willReadFrequently: true }); if (!context) throw new Error("Canvas 2D context is unavailable."); context.clearRect(0, 0, width, height); context.drawImage(image, 0, 0); const pixels = context.getImageData(0, 0, width, height).data; let redTotal = 0; let greenTotal = 0; let blueTotal = 0; let alphaTotal = 0; for (let i = 0; i < pixels.length; i += 4) { const alpha = pixels[i + 3]; if (alpha === 0) continue; redTotal += pixels[i] * alpha; greenTotal += pixels[i + 1] * alpha; blueTotal += pixels[i + 2] * alpha; alphaTotal += alpha; } if (alphaTotal === 0) throw new Error("Image has no visible pixels."); const rgb = { r: Math.round(redTotal / alphaTotal), g: Math.round(greenTotal / alphaTotal), b: Math.round(blueTotal / alphaTotal) }; const hex = "#" + [rgb.r, rgb.g, rgb.b].map(value => value.toString(16).padStart(2, "0")).join(""); return { hex, rgb, alphaCoverage: alphaTotal / (width * height * 255) }; }

Using the 8-bit alpha value from 0 to 255, the calculation is round(sum(channel × alpha) ÷ sum(alpha)). The denominator is total alpha rather than pixel count because transparent and partially transparent pixels carry different weights. Fully transparent pixels are skipped, so their invisible stored RGB data cannot distort the result; partially transparent pixels contribute in proportion to their opacity. The HEX conversion pads every channel to two lowercase hexadecimal digits.

Load an image without losing pixel access

Canvas security can prevent pixel reads. A same-origin image can normally be sampled, while a remote image needs CORS permission from its server and may require crossOrigin to be set before its src. Without the necessary permission, getImageData() throws a SecurityError instead of returning pixel data.

Handle decode failures, invalid dimensions, an unavailable 2D context, and zero total alpha as separate errors. Throw or display an error for each case instead of retaining an older color that could be mistaken for the new image’s result. An animated image also requires care: an Image element exposes a decoded frame rather than averaging every frame or weighting them by duration. Browser orientation handling, color management, and wide-gamut conversion can vary by format and browser.

Run the JavaScript workflow with a local file

  1. Listen for a file selection. Read the first selected File from a file input’s change event.
  2. Create a local object URL. Assign that URL to an Image and await image.decode() before calculating the result.
  3. Call getAverageColor(image). Use the returned hex, rgb, and alphaCoverage values in your application.
  4. Release the object URL. Revoke it in a finally block after processing succeeds or fails.

Example local-file workflow:

const input = document.querySelector("input[type=file]"); input.addEventListener("change", async () => { const file = input.files[0]; if (!file) return; const url = URL.createObjectURL(file); try { const image = new Image(); image.src = url; await image.decode(); const result = getAverageColor(image); console.log(result.hex, result.rgb, result.alphaCoverage); } catch (error) { console.error("Could not calculate average color:", error); } finally { URL.revokeObjectURL(url); } });

This example performs no upload: the object URL refers to the locally selected file inside the browser. For a production application, validate the accepted file type and size before decoding, and replace the console output with your own interface or design workflow.

Choose full-resolution or sampled analysis

The function above uses a canvas at the decoded image dimensions, so it reads every pixel exposed at that size. This is straightforward for ordinary images, but canvas memory use grows with both width and height. A sampled implementation can first scale the image proportionally to a chosen pixel budget, although browser interpolation may then slightly change the resulting color.

Analysis approachPixel set usedMain consideration
Full-resolution JavaScriptAll canvas pixels at the decoded dimensions; zero-alpha pixels are then skippedDirect result for that canvas, with higher memory use
Sampled JavaScriptA browser-resampled canvas limited by a developer-selected pixel budgetLower memory use, but interpolation can affect the HEX
Image Average Color FinderAt most 1,048,576 canvas pixels, with source and sample dimensions displayedUses proportional downsampling for larger images and keeps processing local

Another program can legitimately return a different HEX if it uses full-resolution pixels, another downsample size, gamma-aware or perceptual math, another animation frame, or different color management. The arithmetic average is also not perceptual clustering: red and blue pixels can produce a purple average even when no purple pixel existed, while a small bright accent can be diluted by a large neutral background.

Compare the result with the local finder

When you do not need to maintain JavaScript, the Image Average Color Finder applies the same alpha-weighted arithmetic rule in the current browser tab. The file and sampled pixels are not uploaded to Lizely or an image-analysis service.

  1. Choose the image. Select a PNG, JPEG, WebP, GIF, BMP, or AVIF file that is no larger than 20 MB.
  2. Wait for local decoding. Review the displayed HEX, decimal RGB, alpha coverage, and source and sample dimensions.
  3. Copy and validate the color. Click the visible HEX value to copy it, then check the swatch in the design context where it will be used.

The selected file must also be nonempty and use a supported browser image MIME type. After decoding, neither image edge may exceed 20,000 pixels, and the source may not exceed 40 million pixels. These compressed and decoded safeguards reduce the chance that a small file expands into excessive canvas memory. Unsupported data, decode failures, unavailable canvas access, invalid dimensions, and an image with no visible pixels produce a clear error and no stale result.

Images at or below 1,048,576 pixels are read at their decoded dimensions; larger images are scaled proportionally so the analysis canvas remains within that pixel budget. Coverage is the total sampled alpha divided by the maximum possible alpha across the sample. Animated formats are evaluated from the frame exposed when the browser finishes its initial decode, not across the full animation.

Verify the HEX in its intended context

The preview swatch is useful for checking that the returned number looks plausible, but its appearance still depends on the display, browser, surrounding theme, and human visual adaptation. An average is not proof of brand compliance, accessibility contrast, print matching, paint matching, or perceptual similarity. Use the Color Contrast Checker for text and background contrast, and the Color Difference Calculator when you need a defined color-difference metric.

The copied value always contains exactly a hash followed by six lowercase hexadecimal digits. If browser policy denies clipboard permission, the value remains visible and selectable instead of falsely reporting a successful copy. The finder does not alter or export the source file, and it does not inspect or preserve EXIF data, ICC profiles, camera metadata, filenames beyond display, or hidden text chunks.

For reproducible design work, record the input file, browser, displayed source and sample dimensions, and returned value. If you need the most frequent colors, separated swatches, or subject-aware extraction instead of one arithmetic average, use the Color Palette Generator.