Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

Encode a random image using MozJPEG in WebAssembly

node v12.22.12
version: master
endpointsharetweet
This snippet downloads a random image from unsplash.com, decodes it and encodes it again using the MozJPEG encoder.
const fetch = require('node-fetch'); const wasm_image_loader = require('@saschazar/wasm-image-loader'); // needed to decode JPEG const wasm_mozjpeg = require('@saschazar/wasm-mozjpeg'); const defaultOptions = require('@saschazar/wasm-mozjpeg/options'); // fully populated options object crucially needed! // 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())); const width = 800; // the image's width const height = 600; // the image's height const options = defaultOptions; // MozJPEG's options Promise.all([fetchImage(), wasm_image_loader(), wasm_mozjpeg()]) .then(([buffer, decoder, encoder]) => { // 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 // encode raw RGB image into JPEG format using the MozJPEG encoder and its default options const encoded = encoder.encode(decoded, width, height, channels, options); // clean up WebAssembly memory decoder.free(); encoder.free(); return encoded; }) .then(console.log); // FF D8 FF indicates the magic number of a JPEG image
Loading…

no comments

    sign in to comment