aboutsummaryrefslogtreecommitdiff
path: root/build/js/io/encoders/bmp.js
blob: 4a443375f11d4ade9dadd9c625302ad31f7c66d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// BMP encoder. 24-bit (opaque) or 32-bit BGRA with a BITMAPV4HEADER (alpha).

export function encodeBMP(imageData, { alpha = true } = {}) {
  const { width: w, height: h, data } = imageData;
  const bpp = alpha ? 4 : 3;
  const rowSize = alpha ? w * 4 : Math.ceil((w * 3) / 4) * 4;
  const pixelBytes = rowSize * h;
  const dibSize = alpha ? 108 : 40;
  const offset = 14 + dibSize;
  const buf = new ArrayBuffer(offset + pixelBytes);
  const v = new DataView(buf);
  // BITMAPFILEHEADER
  v.setUint8(0, 0x42); v.setUint8(1, 0x4d);
  v.setUint32(2, buf.byteLength, true);
  v.setUint32(10, offset, true);
  // DIB header
  v.setUint32(14, dibSize, true);
  v.setInt32(18, w, true);
  v.setInt32(22, h, true); // bottom-up
  v.setUint16(26, 1, true);
  v.setUint16(28, bpp * 8, true);
  v.setUint32(30, alpha ? 3 : 0, true); // BI_BITFIELDS : BI_RGB
  v.setUint32(34, pixelBytes, true);
  v.setInt32(38, 2835, true); // 72 dpi
  v.setInt32(42, 2835, true);
  if (alpha) {
    v.setUint32(54, 0x00ff0000, true); // R mask
    v.setUint32(58, 0x0000ff00, true); // G mask
    v.setUint32(62, 0x000000ff, true); // B mask
    v.setUint32(66, 0xff000000, true); // A mask
    v.setUint32(70, 0x73524742, true); // 'sRGB'
  }
  const out = new Uint8Array(buf);
  for (let y = 0; y < h; y++) {
    let o = offset + (h - 1 - y) * rowSize;
    let i = y * w * 4;
    for (let x = 0; x < w; x++, i += 4) {
      out[o++] = data[i + 2];
      out[o++] = data[i + 1];
      out[o++] = data[i];
      if (alpha) out[o++] = data[i + 3];
    }
  }
  return new Blob([buf], { type: 'image/bmp' });
}