Browser Image Processing: Local Compute, Storage and Memory
Browser Image Processing: Local Compute, Storage and Memory
Search
Ask the AI

Browser Image Processing: Local Compute, Storage and Memory

The site’s character library reads local images, produces masks, colour layers and SVG, and can save assets in the current browser. “Upload” here means file selection; the processing module does not send the source image to the server.

There was exactly one constraint: nothing is uploaded; all compute and all storage happen on the visitor’s device.

Client-side processing reduces origin image computation. Page caching lowers request cost; near-zero CPU still depends on hits, dynamic features and traffic, which require monitoring.

After implementation, I found that client-side processing also reduced several other kinds of server-side work.

Which server tasks local processing reduces

Storage. Images stay on the visitor’s device, so the server does not need a location, retention period, or cleanup process for those images.

Without receiving these images, this processing path needs no server upload store or image-moderation pipeline. Design sharing, synchronisation and other collection features according to their own data flows.

Privacy obligations. The server does not receive these images and therefore does not store, retain, or delete them.

Concurrency. Five simultaneous users would compete for the single-core server’s CPU. Client-side processing distributes that work across their own devices.

Client-side processing therefore changes compute, storage, moderation, and image-data management together.

How the whole pipeline runs in a browser

Input is an image file; output is a set of SVG layers with path data. Five steps, each with either a ready browser API or a pure-JS implementation.

Decode. Load an image with URL.createObjectURL and <img>, wait for onload, draw it to a canvas, and obtain the RGBA array with getImageData. Passing a target size to drawImage also uses the browser’s image scaler.

The classical path estimates background from edge colours and connectivity, suiting some simple backdrops. AI masks are another option and still need inspection. The current AI module uses ONNX Runtime Web through WASM; quality depends on model, preprocessing and threshold.

Layering. k-means colour clustering over the foreground pixels, splitting the character into flat colour regions. The cluster count is the “layer count” the user sees.

Connected components. One colour cluster may be scattered across several disjoint areas — two sleeves, say — so components are labelled separately and tiny fragments discarded.

Vectorisation. Contour-trace each component into a point list, simplify with Douglas-Peucker, and emit SVG path data.

Pixel processing stays local. The AI path downloads runtime, WASM and model assets; cache state and other page features determine later requests. The whole page is not a model-only network client.

Storage: IndexedDB and its price

IndexedDB stores structured data per origin, browser profile and configuration. Quotas depend on browser policy and disk space, and data can be evicted. Handle quota errors, provide export and request persistent storage when appropriate.

The interface needs to explain that clearing browser data also deletes the asset library, so users can export their work beforehand.

Export is therefore a required component of this architecture. Users need a way to save a copy before clearing data stored in their browser.

Private browsing may provide temporary IndexedDB or restrict it. Test opening, writing and reading, and explain session-end retention.

ZIP export needs no compression library

Stored ZIP avoids a compression dependency, but SVG and JSON often compress well. Compare export bytes, dependency size and processing time rather than inferring the entire package’s compressibility from PNG.

A basic stored ZIP uses local headers, central directory, end record and CRC32. The small-file writer must also handle UTF-8 flags, lengths and offsets. Implement ZIP64 or reject inputs beyond classic limits. CRC32 detects errors rather than authenticating content.

CRC32 via a lookup table, built lazily on first use:

var TABLE = null;
function crcTable() {
  if (TABLE) return TABLE;
  TABLE = new Uint32Array(256);
  for (var n = 0; n < 256; n++) {
    var c = n;
    for (var k = 0; k < 8; k++) {
      c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
    }
    TABLE[n] = c >>> 0;
  }
  return TABLE;
}

Using ZIP’s uncompressed mode removed the need for a compression library here.

Model downloads, caches and other costs

AI matting first requires downloading a segmentation model to the visitor’s device. The client-side design needs to make that download cost clear.

The implementation needs to handle the following points:

Fetch on demand. Request the model only when the user selects AI mode, so visitors who only browse the page do not have to download it.

Show progress. A download of tens of megabytes with no feedback is indistinguishable from a hang. Read the fetch body as a stream and accumulate:

var reader = res.body.getReader();
var received = 0;
(function pump() {
  return reader.read().then(function (r) {
    if (r.done) return assemble();
    received += r.value.length;
    onProgress(received, total);      // total from content-length
    return pump();
  });
}());

Versioned content URLs and suitable cache headers can reduce repeated downloads. Eviction, private sessions and updates can cause another request; handle cache misses.

The original account describes difficult images failing with int8 and improving with fp16. Preserve model versions, preprocessing, thresholds and samples with that observation. It does not establish generally lossless fp16. Raw int8 and fp16 weight bytes usually differ by about twofold; the complete runtime download need not.

Main-thread work and responsiveness

Client-side computation must account for the main thread handling both rendering and interaction. A loop that occupies it for a few hundred milliseconds can pause buttons, scrolling, and the processing indicator for that period.

A 1024×1024 image has 1,048,576 pixels; elapsed time depends on the operation, device and backend. Time pixel loops and inference separately.

Web Workers can run long loops using messages and transferable buffers. SharedArrayBuffer permits explicit shared memory under browser security prerequisites. The current AI configuration uses single-threaded WASM without a proxy worker; the snippet illustrates a possible later separation.

Structured cloning copies an ordinary ArrayBuffer. Transferring it moves storage and detaches the sender’s buffer, reducing large copies. Message scheduling and other work still have costs.

// the second argument is the transfer list; ownership moves to the worker
worker.postMessage({ pixels: imageData.data.buffer, w, h },
                   [imageData.data.buffer]);
// note: after transfer the sender's buffer has length 0 and is unusable

After the transfer, the originating thread can no longer access that memory, since ownership has moved to the receiver. If the original thread still needs the data, it can copy the buffer first and transfer the copy.

OffscreenCanvas additionally hands the canvas itself to a worker, moving drawing and pixel access off the main thread entirely. Support arrived late on mobile Safari, so it needs feature detection and a fallback.

Mobile memory pressure and page termination

Mobile memory pressure can terminate a page, with thresholds depending on device, OS and other processes. Some allocations can throw first. Handle catchable failures and test termination behaviour on real devices.

Memory termination may appear as a blank page or a spontaneous reload. Once the execution context has ended, try/catch and error reporting cannot run. Large inputs also need testing on a phone.

A 4000×3000 RGBA8 buffer occupies 48,000,000 bytes, about 45.8 MiB; four full-sized RGBA buffers use about 183.1 MiB. The compressed source may be 3 MB. Peak memory also depends on resize dimensions, mask channels, decoding and inference tensors, so this does not define a universal crash threshold.

The following constraints help manage large images:

  • Resize before later processing when appropriate. Reducing a 4000-pixel longest side to 2048 retains about 26.2% of the same-aspect buffer area; decoding can still allocate the original image, and detail is lost.
  • Release unused references and object URLs. Resetting canvas dimensions clears its drawing buffer; actual memory reclamation is browser-managed.
  • Manage intermediates for peak memory, keeping buffers needed by subsequent stages and avoiding unintended duplicates.

Check memory pressure on a real phone. Desktop browsers usually have gigabytes of headroom, so a passing desktop test still needs a large-image test on the target phone.

When not to do this

The approach’s scope also depends on sharing requirements and model cost.

Teams can share exported files, peer-to-peer transfers or server-synchronised assets. Server storage requires its own retention, access and content-handling design.

Compare full model download and reuse, upload, queuing, inference and result-return times, alongside offline and privacy needs. Large models and long inference add cost; the actual workflow determines the choice.

IndexedDB is isolated by origin and browser profile and does not automatically sync devices. Export/import, a user-selected sync folder, peer-to-peer transfer or server synchronisation can provide that function.

For one-off image conversion, format processing, or local analysis whose results stay with one user, client-side processing can reduce both server computation and data-management work.

A worked example of this pattern is live on the site: the image to ANSI art converter decodes, scales, searches masks and emits the file entirely in the browser, with nothing uploaded.

Leave a Reply

Scroll down