jpeg-js

0.4.4 · active · verified Sun Apr 19

jpeg-js is a pure JavaScript library designed for encoding and decoding JPEG images without relying on native binaries or external dependencies. This makes it suitable for various JavaScript environments, including Node.js and browsers (browser support was explicitly added in v0.4.0). It offers synchronous APIs for converting raw image data to the JPEG format and vice-versa, providing direct control over image processing. The current stable version is 0.4.4, released in June 2022. The project has a relatively slow release cadence, with the most recent updates focusing on bug fixes and minor feature enhancements. Its primary differentiating factor is its complete JavaScript implementation, beneficial for environments with strict dependency constraints or where native modules are problematic. However, a significant trade-off is its performance: it is a CPU-blocking library and is considerably slower than native alternatives like `sharp` or browser-native `Canvas API`, which is a crucial consideration for any performance-sensitive application.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates both decoding an existing JPEG file and encoding raw RGBA pixel data into a new JPEG file, highlighting common usage patterns and important options.

import * as fs from 'fs';
import * as jpeg from 'jpeg-js';

// --- Decoding JPEG ---
const jpegData = fs.readFileSync('path/to/your/image.jpg');
try {
  const rawImageData = jpeg.decode(jpegData, { 
    useTArray: false, // Decode pixels into a Buffer (Node.js) or Uint8Array (browser)
    formatAsRGBA: true,
    maxResolutionInMP: 100, // Limit max resolution to prevent OOM errors
    maxMemoryUsageInMB: 512 // Limit max memory to prevent OOM errors
  });
  console.log('Decoded image dimensions:', rawImageData.width, rawImageData.height);
  // rawImageData.data is a Buffer (Node.js) or Uint8Array (browser) containing pixel data
} catch (error) {
  console.error('Error decoding JPEG:', error.message);
}

// --- Encoding JPEG ---
const width = 320;
const height = 180;
// Allocate a Buffer for RGBA pixel data. JPEGs ignore the alpha channel.
const frameData = Buffer.alloc(width * height * 4); 
let i = 0;
while (i < frameData.length) {
  frameData[i++] = 0xff; // Red
  frameData[i++] = 0x00; // Green
  frameData[i++] = 0x00; // Blue
  frameData[i++] = 0xff; // Alpha (ignored in JPEG)
}

const rawImageData = {
  data: frameData,
  width: width,
  height: height
};

try {
  const jpegImageData = jpeg.encode(rawImageData, 50); // Quality 0-100
  fs.writeFileSync('output.jpg', jpegImageData.data);
  console.log('JPEG encoded successfully to output.jpg');
} catch (error) {
  console.error('Error encoding JPEG:', error.message);
}

view raw JSON →