Four common edits, one simple idea

Turning a photo black and white, making a negative, lightening a dark shot, or adding punch to a flat one. These are some of the most common image edits people make.

They feel like "photo editing", so it is easy to assume a server or a big app has to do them. In fact, each one is a short loop over a list of numbers. Your browser already has that list once it has opened the image.

I built four small browser tools for these edits: grayscale, invert colours, brightness and contrast. In this article I show the one idea they share, the exact formula each one uses, and where the approach stops being enough.

An image is just a long list of numbers

When you draw an image on a <canvas> and call getImageData(), you get an ImageData object. Its data property is a Uint8ClampedArray: one flat list with four numbers per pixel.

  • data[i]: Meaning: Red. Range: 0 to 255.
  • data[i + 1]: Meaning: Green. Range: 0 to 255.
  • data[i + 2]: Meaning: Blue. Range: 0 to 255.
  • data[i + 3]: Meaning: Alpha (opacity). Range: 0 to 255.

The first pixel is at index 0, the second at index 4, and so on, row by row from the top left. A 1,000 × 1,000 image gives a list of four million numbers.

The "clamped" part matters a lot for these tools. If you write 280 into this array, it stores 255. If you write -5, it stores 0. If you write 56.85, it stores 57. That one property does the clipping and rounding work for brightness and contrast.

So every adjustment follows the same three steps:

  1. Draw the image on a canvas.
  2. Read the pixels with getImageData(), change the numbers, write them back with putImageData().
  3. Export the canvas with toBlob() as PNG, JPG or WebP.

The four formulas

All four tools change only red, green and blue. None of them touches the alpha value, so transparent areas stay transparent.

Grayscale. Each pixel becomes one gray value, written to all three channels:

gray = round(0.299 × R + 0.587 × G + 0.114 × B)

The weights are not equal because our eyes see green as much brighter than blue. A plain average would make blue skies look too light. Blue RGB (80, 120, 200) becomes 117 on all three channels.

Invert. Each channel becomes its opposite: 255 − value. Black turns white, red turns cyan, and (20, 100, 240) becomes (235, 155, 15). Unlike grayscale, the result usually stays colourful.

Brightness. The same number is added to every channel. In my tool it is a whole number from −100 to +100. At +30, (80, 120, 200) becomes (110, 150, 230). It is a fixed step on the 0 to 255 scale, not a percentage.

Contrast. Each channel is pushed away from, or pulled towards, the middle value 128. For a setting c from −100 to +100:

factor = 259 × (c + 255) / (255 × (259 − c)) new = factor × (value − 128) + 128

At 0 the factor is exactly 1, so nothing changes. At +100 it is about 2.268, and at −100 it is about 0.439. Even at −100 the image does not turn flat gray; the differences between tones just shrink to less than half.

The code: one page, four adjustments

This is a complete page. Choose an image, pick an adjustment, and move the slider. Save it as an HTML file and open it in any modern browser.

<!doctype html> <meta charset="utf-8"> <input type="file" id="pick" accept="image/*"> <select id="mode"> <option value="gray">Grayscale</option><option value="invert">Invert</option> <option value="bright">Brightness</option><option value="contrast">Contrast</option> </select> <input type="range" id="amount" min="-100" max="100" value="30"> <br><canvas id="out"></canvas> <script> const canvas = document.getElementById('out'); const ctx = canvas.getContext('2d', { willReadFrequently: true }); let img = null; function render() { if (!img) return; canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; ctx.drawImage(img, 0, 0); // always start from the untouched pixels const mode = document.getElementById('mode').value; const amount = Number(document.getElementById('amount').value); const factor = (259 * (amount + 255)) / (255 * (259 - amount)); const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height); const d = pixels.data; // [r, g, b, a, r, g, b, a, ...] for (let i = 0; i < d.length; i += 4) { if (mode === 'gray') { d[i] = d[i + 1] = d[i + 2] = Math.round(0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2]); continue; } for (let c = 0; c < 3; c++) { // d[i + 3] (alpha) is never touched if (mode === 'invert') d[i + c] = 255 - d[i + c]; if (mode === 'bright') d[i + c] = d[i + c] + amount; if (mode === 'contrast') d[i + c] = factor * (d[i + c] - 128) + 128; } } ctx.putImageData(pixels, 0, 0); } document.getElementById('pick').addEventListener('change', (e) => { if (!e.target.files[0]) return; img = new Image(); img.onload = render; img.src = URL.createObjectURL(e.target.files[0]); }); document.getElementById('mode').addEventListener('change', render); document.getElementById('amount').addEventListener('input', render); </script> 

The key lines:

  • URL.createObjectURL(file) gives the <img> a local address for the file. The browser reads it from your disk; nothing travels over the network.
  • willReadFrequently: true tells the browser you will read pixels back often. It can then keep the canvas in normal memory, which makes getImageData() cheaper.
  • ctx.drawImage(img, 0, 0) runs on every change. Each adjustment starts from the original pixels, so moving the slider back to 0 really gives the original. If you edited the canvas in place, every move would stack on the last one.
  • i += 4 jumps from one pixel to the next. Inside the loop, c < 3 stops before alpha.
  • Brightness and contrast write values like 290 or 56.85 without any Math.min or Math.round. The Uint8ClampedArray clamps and rounds them on its own.

I tested this page in headless Chromium with four colour swatches. Every adjustment gave the values the formulas above predict, to within one step of rounding.

Two details from the real tools

A lookup table for contrast. The contrast formula has a multiplication, a subtraction and an addition per channel. But a channel can only hold 256 different values, so the tool works out all 256 answers once and then just looks them up:

const factor = contrastFactor(amount), lookup = new Uint8ClampedArray(256); for (let v = 0; v < 256; v++) lookup[v] = Math.max(0, Math.min(255, factor * (v - 128) + 128)); for (let i = 0; i < data.length; i += 4) { data[i] = lookup[data[i]]; data[i + 1] = lookup[data[i + 1]]; data[i + 2] = lookup[data[i + 2]]; } 

The same trick works for any adjustment where the new value depends only on the old value of that channel. Brightness and invert could use it too; grayscale cannot, because it mixes three channels.

Small strips, so the page stays usable. The live preview is reduced to fit within 900 px, which is quick. The saved file, though, uses every pixel of the original, and a 20 MP photo is 80 million numbers. The tools process the full-size canvas in strips of 64 rows and let the browser breathe between strips:

for (let y = 0; y < canvas.height; y += 64) { if (!valid()) throw new Error("Preparation stopped."); applyRows(canvas, y, Math.min(64, canvas.height - y)); await pause(); // setTimeout(resolve, 0) } 

The valid() check is what makes the Stop button work. It also stops the job if you change a setting or remove the image while it runs, so an outdated file is never saved.

One more small detail: JPG cannot store transparency. When you choose JPG, the tools paint white behind the image after the adjustment, using globalCompositeOperation = "destination-over". Transparent areas become white, and that white is not adjusted itself.

Honest limits

These are simple, fast formulas, and that comes with trade-offs:

  • Clipping loses detail for good. At +60 brightness, every channel above 195 becomes 255. Turning brightness back down on the saved file cannot separate those pixels again. The same is true for strong contrast, at both ends.
  • Brightness is not exposure. Adding a fixed number lifts shadows and highlights by the same amount. Camera-style exposure and curves tools work differently. My tools do not offer curves, levels, or a partial-strength grayscale.
  • Not colour-managed. The formulas work on the decoded 0 to 255 values the browser gives the canvas. They do not use colour profiles, so grayscale is not a print-accurate luminance conversion.
  • Different colours can become the same gray. A red and a green of similar lightness may look almost identical after grayscale.
  • Semi-transparent edges can shift slightly. Browsers can round the colour of partly transparent canvas pixels by a small amount.
  • Inverting is not film scanning. It reverses a basic digital negative, but it does not remove the orange mask of colour film.
  • Size limits. The tools accept up to five images of 10 MB each. Each image may have up to 20 MP and 16,384 px per side. A batch may hold 40 MP, and a saved file may reach 96 MB.

What stays on your device

Everything that touches your pixels happens in the page. The image is read from your disk, adjusted on a canvas, encoded with toBlob(), and saved with a normal download link. Nothing is uploaded at any step.

There is one exception, and it carries no image data. If you add a HEIC photo and your browser cannot open HEIC itself, the tool downloads a decoder script from jsDelivr. The request fetches code; your photo stays on the device.

The original file is never changed. The tool only ever reads it, and every saved result is a new file.

Closing thought

Grayscale, invert, brightness and contrast look like four features. Under the hood they are four one-line formulas applied to a Uint8ClampedArray. Once you see an image as a list of numbers, many "photo effects" become a loop you can write in a few minutes.