Calculate mean color of random image using WebAssembly

node v12.22.12
version: master
endpointsharetweet
This snippet downloads a random image from unsplash.com, decodes it and calculates the mean color value
const fetch = require('node-fetch'); const wasm_image_loader = require('@saschazar/wasm-image-loader'); // needed to decode JPEG const wasm_mean_color = require('@saschazar/wasm-mean-color'); // fetch a random 800x600 JPEG image from unsplash.com const RANDOM_URL = 'https://source.unsplash.com/random/800x600'; const fetchImage = async () => new Uint8Array(await fetch(RANDOM_URL).then(res => res.buffer())); Promise.all([fetchImage(), wasm_image_loader(), wasm_mean_color()]) .then(([buffer, decoder, mean]) => { // log source JPEG image console.log(buffer); // FF D8 FF indicates the magic number of a JPEG image // decode JPEG image into raw RGB Uint8Array const channels = 3; // desired output channels (3 for RGB) const decoded = decoder.decode(buffer, buffer.length, channels); // buffer, length, desired channels // calculate the mean color of the decoded image const meanColor = mean.getColor(decoded, decoded.length, channels); // clean up WebAssembly memory decoder.free(); return meanColor; }) .then(console.log); // Hex-String of mean color
Loading…

no comments

    sign in to comment