Encode sample AVIF image using MozJPEG encoder

node v12.22.12
version: master
endpointsharetweet
This snippet fetches an AVIF-encoded sample image and decodes it. Afterwards, it encodes it again using the MozJPEG encoder to show the difference in file size between these file formats.
const fetch = require('node-fetch'); const wasm_avif = require('@saschazar/wasm-avif'); // needed to decode AVIF const wasm_mozjpeg = require('@saschazar/wasm-mozjpeg'); const defaultOptions = require('@saschazar/wasm-mozjpeg/options'); // fully populated options object crucially needed! // fetch a sample AVIF image from GitHub const SAMPLE_URL = 'https://github.com/AOMediaCodec/av1-avif/blob/cfffa52/testFiles/Netflix/avif/sdr_cosmos01650_cicp1-13-6_yuv444_full_qp10.avif?raw=true'; const fetchImage = async () => new Uint8Array(await fetch(SAMPLE_URL).then(res => res.buffer())); const options = { ...defaultOptions, // MozJPEG's options in_color_space: 12, // let encoder know, that we're dealing with RGBA input buffer }; Promise.all([fetchImage(), wasm_avif(), wasm_mozjpeg()]) .then(([buffer, decoder, encoder]) => { // log source AVIF image console.log(buffer); // decode AVIF image into raw RGB Uint8Array const alpha = true; // return RGBA instead of RGB const decoded = decoder.decode(buffer, buffer.length, alpha); // buffer, length, return alpha channel? const { channels, width, height } = decoder.dimensions(); // 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