BMP Image Encoder/Decoder

1.0.9 · active · verified Tue Apr 21

bmp-ts is a pure TypeScript library designed for encoding and decoding BMP image files. It currently stands at version 1.0.9, with a release cadence focused on addressing bug fixes and minor enhancements. The library distinguishes itself by offering comprehensive support for all common BMP bit depths, including 1-bit, 4-bit, 8-bit, 16-bit, 24-bit, and 32-bit images. It provides granular control over BMP header properties during the encoding process and offers an optional `toRGBA` conversion during decoding for compatibility with other image processing libraries. While it supports various compression methods for decoding, a key limitation is the lack of compression support during encoding, meaning output files will always be uncompressed.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to decode an existing BMP file and encode a new BMP image from raw pixel data using `bmp-ts`.

import bmp from 'bmp-ts';
import * as fs from 'fs';

// --- Decoding a BMP image ---
// Ensure 'example.bmp' exists in the execution directory for this to run.
// You can replace this with any Buffer containing BMP data.
try {
  const bmpBuffer = fs.readFileSync('example.bmp'); 
  const decodedBmpData = bmp.decode(bmpBuffer, { toRGBA: true });
  console.log('Decoded BMP Header:', decodedBmpData.header);
  console.log('Decoded BMP Data length:', decodedBmpData.data.length);
  console.log('Decoded BMP dimensions:', decodedBmpData.header.width, 'x', decodedBmpData.header.height);
} catch (error) {
  console.error('Error decoding example.bmp:', error);
}

// --- Encoding a new BMP image ---
// Create a dummy image buffer (e.g., a 10x10 white image with alpha)
const width = 10;
const height = 10;
const pixelData = Buffer.alloc(width * height * 4, 255); // RGBA white pixels

const bmpDataToEncode = {
  data: pixelData,
  bitPP: 32, // 32-bit RGBA
  width: width,
  height: height
  // Optional: other BMP header fields can be specified here.
};

const encodedRawData = bmp.encode(bmpDataToEncode);
fs.writeFileSync('./output.bmp', encodedRawData.data);
console.log('Encoded 10x10 32-bit white BMP saved to output.bmp');

view raw JSON →