{"id":11147,"library":"jpeg-js","title":"jpeg-js","description":"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.","status":"active","version":"0.4.4","language":"javascript","source_language":"en","source_url":"https://github.com/eugeneware/jpeg-js","tags":["javascript","jpeg","jpg","encoder","decoder","codec","image","js"],"install":[{"cmd":"npm install jpeg-js","lang":"bash","label":"npm"},{"cmd":"yarn add jpeg-js","lang":"bash","label":"yarn"},{"cmd":"pnpm add jpeg-js","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library exports an object with decode/encode methods. For ESM, use `import * as jpeg` to get the module namespace object. For TypeScript, this provides access to `jpeg.decode` and `jpeg.encode`.","wrong":"import jpeg from 'jpeg-js';","symbol":"jpeg","correct":"import * as jpeg from 'jpeg-js';"},{"note":"The `decode` function is a property of the main exported object, not a named export. CommonJS users should `require` the module and access `jpeg.decode`.","wrong":"import { decode } from 'jpeg-js';","symbol":"jpeg.decode","correct":"const jpeg = require('jpeg-js');\nconst decoded = jpeg.decode(buffer);"},{"note":"Similar to `decode`, `encode` is a property of the main exported object. Access it via the module reference.","wrong":"import { encode } from 'jpeg-js';","symbol":"jpeg.encode","correct":"const jpeg = require('jpeg-js');\nconst encoded = jpeg.encode(imageData, quality);"}],"quickstart":{"code":"import * as fs from 'fs';\nimport * as jpeg from 'jpeg-js';\n\n// --- Decoding JPEG ---\nconst jpegData = fs.readFileSync('path/to/your/image.jpg');\ntry {\n  const rawImageData = jpeg.decode(jpegData, { \n    useTArray: false, // Decode pixels into a Buffer (Node.js) or Uint8Array (browser)\n    formatAsRGBA: true,\n    maxResolutionInMP: 100, // Limit max resolution to prevent OOM errors\n    maxMemoryUsageInMB: 512 // Limit max memory to prevent OOM errors\n  });\n  console.log('Decoded image dimensions:', rawImageData.width, rawImageData.height);\n  // rawImageData.data is a Buffer (Node.js) or Uint8Array (browser) containing pixel data\n} catch (error) {\n  console.error('Error decoding JPEG:', error.message);\n}\n\n// --- Encoding JPEG ---\nconst width = 320;\nconst height = 180;\n// Allocate a Buffer for RGBA pixel data. JPEGs ignore the alpha channel.\nconst frameData = Buffer.alloc(width * height * 4); \nlet i = 0;\nwhile (i < frameData.length) {\n  frameData[i++] = 0xff; // Red\n  frameData[i++] = 0x00; // Green\n  frameData[i++] = 0x00; // Blue\n  frameData[i++] = 0xff; // Alpha (ignored in JPEG)\n}\n\nconst rawImageData = {\n  data: frameData,\n  width: width,\n  height: height\n};\n\ntry {\n  const jpegImageData = jpeg.encode(rawImageData, 50); // Quality 0-100\n  fs.writeFileSync('output.jpg', jpegImageData.data);\n  console.log('JPEG encoded successfully to output.jpg');\n} catch (error) {\n  console.error('Error encoding JPEG:', error.message);\n}","lang":"typescript","description":"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."},"warnings":[{"fix":"For performance-critical scenarios, consider using native solutions like `sharp` (Node.js) or the browser's `Canvas API` and Web Workers to offload processing from the main thread.","message":"jpeg-js is a pure JavaScript, synchronous, and CPU-blocking library. It is significantly slower than native image processing libraries (e.g., `sharp` in Node.js or the native Canvas API in browsers). Using it for large images or in performance-critical applications can lead to application unresponsiveness.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Upgrade to `jpeg-js@0.4.2` or higher. Always use `Buffer.from()`, `Buffer.alloc()`, or `Buffer.allocUnsafe()` for creating Buffers in your application code, as demonstrated in the quickstart.","message":"The `new Buffer()` constructor is deprecated in Node.js (since v6.0.0) and can lead to security vulnerabilities. Earlier versions of `jpeg-js` (before v0.4.2) might have used this constructor internally or encouraged its use in examples.","severity":"breaking","affected_versions":"<0.4.2"},{"fix":"Catch potential errors during `jpeg.decode`. Adjust `maxResolutionInMP` and `maxMemoryUsageInMB` in the decode options if you intend to process very large images, but be mindful of memory consumption.","message":"Since v0.4.0, `jpeg-js` introduced `maxResolutionInMP` and `maxMemoryUsageInMB` options to prevent Out Of Memory (OOM) errors when processing excessively large or malformed JPEGs. Decoding images exceeding these limits will throw an error.","severity":"gotcha","affected_versions":">=0.4.0"},{"fix":"Upgrade to `jpeg-js@0.4.4` or higher, which includes a fix to rethrow a more helpful error in these scenarios. For browser environments, ensure you have a `Buffer` polyfill if `useTArray: false` is desired, or explicitly use `useTArray: true` in decode options to get `Uint8Array`.","message":"When running in environments without a global `Buffer` object (e.g., some browser setups or older Node.js versions without explicit polyfills), you might encounter `ReferenceError: Buffer is not defined`.","severity":"gotcha","affected_versions":"<0.4.4"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Increase the `maxResolutionInMP` option in `jpeg.decode()` if you expect to handle larger images, e.g., `{ maxResolutionInMP: 200 }`.","cause":"The input JPEG image's resolution exceeds the `maxResolutionInMP` limit set in the decode options (default 100MP).","error":"Error: Maximum resolution exceeded while decoding JPEG. (max: 100MP)"},{"fix":"Increase the `maxMemoryUsageInMB` option in `jpeg.decode()` if you have more memory available and expect to handle memory-intensive images, e.g., `{ maxMemoryUsageInMB: 1024 }`.","cause":"The decoding process requires more memory than allowed by the `maxMemoryUsageInMB` limit (default 512MB).","error":"Error: Maximum memory usage exceeded while decoding JPEG. (max: 512MB)"},{"fix":"If running in a browser, ensure you have a `Buffer` polyfill or set `useTArray: true` in the `jpeg.decode()` options to receive pixel data as `Uint8Array`. Upgrade to `jpeg-js@0.4.4` for improved error messaging.","cause":"The code is being executed in an environment where the Node.js `Buffer` global is not available (e.g., a pure browser environment without a polyfill) and `jpeg-js` attempts to use it.","error":"ReferenceError: Buffer is not defined"},{"fix":"Use the correct import syntax: `import * as jpeg from 'jpeg-js';` for ESM, then access `jpeg.decode()` or `jpeg.encode()`. For CommonJS, `const jpeg = require('jpeg-js');` is correct.","cause":"This usually occurs when trying to use named import syntax (e.g., `import { decode } from 'jpeg-js';`) for a module that exports an object with properties, rather than named exports.","error":"TypeError: jpeg.decode is not a function"}],"ecosystem":"npm"}