Encode random JPEG in WebP using WebAssembly

node v12.22.12
version: master
endpointsharetweet
This snippet fetches a random image from unsplash.com, decodes it and encodes it again using the WebP encoder.
const fetch = require('node-fetch'); const wasm_image_loader = require('@saschazar/wasm-image-loader'); // needed to decode JPEG const wasm_webp = require('@saschazar/wasm-webp'); const defaultOptions = require('@saschazar/wasm-webp/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; // WebP's options Promise.all([fetchImage(), wasm_image_loader(), wasm_webp()]) .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 const decoded = decoder.decode(buffer, buffer.length, channels); // buffer, length, desired channels (3 for RGB) // encode raw RGB image into WebP format using default options const encoded = encoder.encode(decoded, width, height, channels, options); // clean up WebAssembly memory decoder.free(); encoder.free(); return encoded; }) .then(console.log); // 52 49 46 46 indicates the magic number of a WebP image
Loading…

no comments

    sign in to comment