dreamega-bmp-codec
v1.0.0
Published
Pure JavaScript BMP encoder and decoder. Read and write BMP files in the browser or Node.js.
Maintainers
Readme
dreamega-bmp-codec
Pure JavaScript BMP encoder and decoder. Read and write BMP files in the browser or Node.js.
Extracted from Dreamega - an AI content creation platform.
Installation
npm install dreamega-bmp-codecUsage
Encoding (ImageData to BMP)
import { encodeBMP } from "dreamega-bmp-codec";
// Get ImageData from a canvas
const canvas = document.querySelector("canvas")!;
const ctx = canvas.getContext("2d")!;
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Encode to BMP
const bmpBlob = encodeBMP(imageData);
// Download
const url = URL.createObjectURL(bmpBlob);
const a = document.createElement("a");
a.href = url;
a.download = "output.bmp";
a.click();Decoding (BMP to ImageData)
import { decodeBMP } from "dreamega-bmp-codec";
// Read a BMP file
const file = inputElement.files[0];
const buffer = await file.arrayBuffer();
const imageData = decodeBMP(buffer);
// Draw to canvas
const canvas = document.createElement("canvas");
canvas.width = imageData.width;
canvas.height = imageData.height;
canvas.getContext("2d")!.putImageData(imageData, 0, 0);API
encodeBMP(imageData: ImageData): Blob
Encode ImageData to a 24-bit BMP file.
- 14-byte file header + 40-byte BITMAPINFOHEADER
- 24-bit color (BGR format)
- Bottom-to-top row order
- Row padding to 4-byte alignment
- 72 DPI resolution (2835 pixels/meter)
decodeBMP(buffer: ArrayBuffer): ImageData
Decode a BMP file to ImageData.
- Supports 24-bit and 32-bit uncompressed BMPs
- Handles both bottom-to-top and top-to-bottom row order
- Validates BMP headers and data integrity
BMP Format Details
The BMP file format consists of:
- File Header (14 bytes): "BM" signature, file size, pixel data offset
- Info Header (40 bytes): dimensions, bit depth, compression, resolution
- Pixel Data: BGR(A) pixels, rows padded to 4-byte boundaries
Features
- Zero dependencies
- Works in browser and Node.js (with ImageData polyfill)
- Correct BMP binary format with proper headers
- Handles row padding for all image widths
License
MIT - see LICENSE
